Files
shadow-over-bishkek001/dialogEditor/src/hooks/useAutoSave.ts
T

32 lines
785 B
TypeScript

import { useState, useEffect, useRef } from 'react';
export function useAutoSave(
value: string,
onSave: (value: string) => void,
delay = 600
): [string, (v: string) => void] {
const [local, setLocal] = useState(value);
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
const savedValueRef = useRef(value);
useEffect(() => {
if (value !== savedValueRef.current) {
savedValueRef.current = value;
setLocal(value);
}
}, [value]);
const handleChange = (v: string) => {
setLocal(v);
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
savedValueRef.current = v;
onSave(v);
}, delay);
};
useEffect(() => () => clearTimeout(timerRef.current), []);
return [local, handleChange];
}