feat: add useGlobalSocketEvent

pull/56/head
moonrailgun 2 years ago
parent c394a4f609
commit fe249db5dd

@ -67,6 +67,18 @@ export class AppSocket {
this.listener.push([`notify:${eventName}`, callback as any]); this.listener.push([`notify:${eventName}`, callback as any]);
} }
/**
*
*/
removeListener(eventName: string, callback: (data: any) => void) {
const index = this.listener.findIndex(
(item) => item[0] === eventName && item[1] === callback
);
if (index >= 0) {
this.listener.splice(index, 1);
}
}
/** /**
* *
* NOTICE: * NOTICE:

@ -20,7 +20,10 @@ export {
openReconfirmModal, openReconfirmModal,
} from '@/components/Modal'; } from '@/components/Modal';
export { Loadable } from '@/components/Loadable'; export { Loadable } from '@/components/Loadable';
export { getGlobalState } from '@/utils/global-state-helper'; export {
getGlobalState,
useGlobalSocketEvent,
} from '@/utils/global-state-helper';
export { getJWTUserInfo } from '@/utils/jwt-helper'; export { getJWTUserInfo } from '@/utils/jwt-helper';
export { dataUrlToFile } from '@/utils/file-helper'; export { dataUrlToFile } from '@/utils/file-helper';
export { export {

@ -1,4 +1,5 @@
import type { AppStore, AppState, AppSocket } from 'tailchat-shared'; import { useEffect } from 'react';
import { AppStore, AppState, AppSocket, useMemoizedFn } from 'tailchat-shared';
let _store: AppStore; let _store: AppStore;
export function setGlobalStore(store: AppStore) { export function setGlobalStore(store: AppStore) {
@ -22,3 +23,25 @@ export function getGlobalSocket(): AppSocket | null {
} }
return _socket; return _socket;
} }
/**
* socket
*/
export function useGlobalSocketEvent<T>(
eventName: string,
callback: (data: T) => void
) {
const fn = useMemoizedFn(callback);
useEffect(() => {
if (_socket) {
_socket.listen(eventName, fn);
}
return () => {
if (_socket) {
_socket.removeListener(eventName, fn);
}
};
}, []);
}

@ -72,6 +72,11 @@ declare module '@capital/common' {
export const getGlobalState: any; export const getGlobalState: any;
export const useGlobalSocketEvent: <T>(
eventName: string,
callback: (data: T) => void
) => void;
export const getJWTUserInfo: () => Promise<{ export const getJWTUserInfo: () => Promise<{
_id?: string; _id?: string;
nickname?: string; nickname?: string;

Loading…
Cancel
Save