feat: add useSocketSubscribeList
This commit is contained in:
parent
9ea006b955
commit
8aaf3c22b7
@ -3,7 +3,7 @@ import { getJWT } from './auth';
|
|||||||
import type { SubscribeEventMap, SocketEventMap } from '../../server/ws/shared';
|
import type { SubscribeEventMap, SocketEventMap } from '../../server/ws/shared';
|
||||||
import { create } from 'zustand';
|
import { create } from 'zustand';
|
||||||
import { useEvent } from '../hooks/useEvent';
|
import { useEvent } from '../hooks/useEvent';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useReducer, useState } from 'react';
|
||||||
|
|
||||||
const useSocketStore = create<{
|
const useSocketStore = create<{
|
||||||
socket: Socket | null;
|
socket: Socket | null;
|
||||||
@ -109,3 +109,35 @@ export function useSocketSubscribe<T>(
|
|||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface UseSocketSubscribeListOptions<K, T> {
|
||||||
|
filter?: (data: T) => boolean;
|
||||||
|
}
|
||||||
|
const defaultFilter = () => true;
|
||||||
|
export function useSocketSubscribeList<
|
||||||
|
K extends keyof SubscribeEventMap = keyof SubscribeEventMap,
|
||||||
|
T = SubscribeEventData<K>
|
||||||
|
>(name: K, options: UseSocketSubscribeListOptions<K, T> = {}): T[] {
|
||||||
|
const { filter = defaultFilter } = options;
|
||||||
|
const { subscribe } = useSocket();
|
||||||
|
const [list, push] = useReducer(
|
||||||
|
(state: T[], data: T) => [...state, data],
|
||||||
|
[] as T[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const cb = useEvent((_data) => {
|
||||||
|
if (filter(_data)) {
|
||||||
|
push(_data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const unsubscribe = subscribe(name, cb);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
}, [name]);
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user