batching events
This commit is contained in:
committed by
Carl-Gerhard Lindesvärd
parent
244aa3b0d3
commit
5e225b7ae6
30
apps/dashboard/src/hooks/useDebounceVal.ts
Normal file
30
apps/dashboard/src/hooks/useDebounceVal.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import debounce from 'lodash.debounce';
|
||||
|
||||
interface DebouncedState<T> {
|
||||
value: T;
|
||||
debounced: T;
|
||||
set: React.Dispatch<React.SetStateAction<T>>;
|
||||
}
|
||||
|
||||
export function useDebounceVal<T>(
|
||||
initialValue: T,
|
||||
delay = 500,
|
||||
options?: Parameters<typeof debounce>[2]
|
||||
): DebouncedState<T> {
|
||||
const [value, setValue] = useState<T>(initialValue);
|
||||
const [debouncedValue, _setDebouncedValue] = useState<T>(initialValue);
|
||||
const setDebouncedValue = useMemo(
|
||||
() => debounce(_setDebouncedValue, delay, options),
|
||||
[]
|
||||
);
|
||||
useEffect(() => {
|
||||
setDebouncedValue(value);
|
||||
}, [value]);
|
||||
|
||||
return {
|
||||
value,
|
||||
debounced: debouncedValue,
|
||||
set: setValue,
|
||||
};
|
||||
}
|
||||
@@ -2,11 +2,22 @@
|
||||
|
||||
import { use, useEffect, useMemo, useState } from 'react';
|
||||
import { useAuth } from '@clerk/nextjs';
|
||||
import debounce from 'lodash.debounce';
|
||||
import useWebSocket from 'react-use-websocket';
|
||||
|
||||
import { getSuperJson } from '@openpanel/common';
|
||||
|
||||
export default function useWS<T>(path: string, onMessage: (event: T) => void) {
|
||||
type UseWSOptions = {
|
||||
debounce?: {
|
||||
delay: number;
|
||||
} & Parameters<typeof debounce>[2];
|
||||
};
|
||||
|
||||
export default function useWS<T>(
|
||||
path: string,
|
||||
onMessage: (event: T) => void,
|
||||
options?: UseWSOptions
|
||||
) {
|
||||
const auth = useAuth();
|
||||
const ws = String(process.env.NEXT_PUBLIC_API_URL)
|
||||
.replace(/^https/, 'wss')
|
||||
@@ -18,6 +29,13 @@ export default function useWS<T>(path: string, onMessage: (event: T) => void) {
|
||||
[baseUrl, token]
|
||||
);
|
||||
|
||||
const debouncedOnMessage = useMemo(() => {
|
||||
if (options?.debounce) {
|
||||
return debounce(onMessage, options.debounce.delay, options.debounce);
|
||||
}
|
||||
return onMessage;
|
||||
}, [options?.debounce?.delay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (auth.isSignedIn) {
|
||||
auth.getToken().then(setToken);
|
||||
@@ -35,7 +53,7 @@ export default function useWS<T>(path: string, onMessage: (event: T) => void) {
|
||||
try {
|
||||
const data = getSuperJson<T>(event.data);
|
||||
if (data) {
|
||||
onMessage(data);
|
||||
debouncedOnMessage(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing message', error);
|
||||
|
||||
Reference in New Issue
Block a user