batching events

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-17 17:13:07 +02:00
committed by Carl-Gerhard Lindesvärd
parent 244aa3b0d3
commit 5e225b7ae6
58 changed files with 2204 additions and 583 deletions

View 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,
};
}

View File

@@ -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);