feat(categories): autosave category changes

This commit is contained in:
Paul
2021-10-30 18:20:12 +01:00
parent e3efe9297d
commit 8bbe8d46ae
5 changed files with 371 additions and 214 deletions

View File

@@ -1,3 +1,7 @@
import isEqual from "lodash.isequal";
import { Inputs, useCallback, useEffect, useRef } from "preact/hooks";
export function debounce(cb: (...args: unknown[]) => void, duration: number) {
// Store the timer variable.
let timer: NodeJS.Timeout;
@@ -13,3 +17,60 @@ export function debounce(cb: (...args: unknown[]) => void, duration: number) {
}, duration);
};
}
export function useDebounceCallback(
cb: (...args: unknown[]) => void,
inputs: Inputs,
duration = 1000,
) {
// eslint-disable-next-line
return useCallback(
debounce(cb as (...args: unknown[]) => void, duration),
inputs,
);
}
export function useAutosaveCallback(
cb: (...args: unknown[]) => void,
inputs: Inputs,
duration = 1000,
) {
const ref = useRef(cb);
// eslint-disable-next-line
const callback = useCallback(
debounce(() => ref.current(), duration),
[],
);
useEffect(() => {
ref.current = cb;
callback();
// eslint-disable-next-line
}, [cb, callback, ...inputs]);
}
export function useAutosave<T>(
cb: () => void,
dependency: T,
initialValue: T,
onBeginChange?: () => void,
duration?: number,
) {
if (onBeginChange) {
// eslint-disable-next-line
useEffect(
() => {
!isEqual(dependency, initialValue) && onBeginChange();
},
// eslint-disable-next-line
[dependency],
);
}
return useAutosaveCallback(
() => !isEqual(dependency, initialValue) && cb(),
[dependency],
duration,
);
}