This commit is contained in:
Morten Olsen
2023-06-16 11:10:50 +02:00
commit bc0d501d98
163 changed files with 16458 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
import { useCallback, useEffect, useRef } from 'react';
type AutoUpdateOptions<TReturn> = {
interval: number;
action: () => Promise<TReturn>;
callback?: (next: TReturn, prev?: TReturn) => void;
};
const useAutoUpdate = <T>(
{ interval, action, callback = () => {} }: AutoUpdateOptions<T>,
deps: any[],
) => {
const prev = useRef<T>();
const actionWithCallback = useCallback(action, [...deps]);
const callbackWithCallback = useCallback(callback, [...deps]);
const update = useCallback(async () => {
const next = await actionWithCallback();
callbackWithCallback(next, prev.current);
prev.current = next;
}, [actionWithCallback, callbackWithCallback]);
useEffect(() => {
let intervalId: NodeJS.Timeout;
const update = async () => {
const next = await actionWithCallback();
callbackWithCallback(next, prev.current);
prev.current = next;
intervalId = setTimeout(update, interval);
};
update();
return () => {
clearTimeout(intervalId);
};
}, [interval, actionWithCallback, callbackWithCallback]);
return update;
};
export { useAutoUpdate };