react-autosave
Version:
A lightweight solution for auto saving controlled form values
53 lines (52 loc) • 1.03 kB
JavaScript
import { useState as h, useEffect as u, useRef as i, useCallback as m } from "react";
function D(e, t) {
const [s, n] = h(e);
return u(() => {
if (typeof window < "u") {
const r = setTimeout(() => {
n(e);
}, t);
return () => {
clearTimeout(r);
};
}
}, [e, t]), s;
}
function y({
data: e,
onSave: t,
interval: s = 2e3,
saveOnUnmount: n = !0
}) {
const r = i(!1), o = i(e), f = i(t), l = D(e, s), c = m((a) => {
f.current(a), r.current = !1;
}, []);
u(() => {
if (!r.current)
try {
JSON.stringify(o.current) !== JSON.stringify(e) && (r.current = !0);
} catch {
r.current = !0;
}
}, [e]), u(() => {
o.current = e;
}, [e]), u(() => {
f.current = t;
}, [t]), u(() => {
r.current && c(l);
}, [c, l]), u(
() => () => {
n && r.current && c(o.current);
},
[c, n]
);
}
const g = ({
element: e = null,
...t
}) => (y(t), e);
export {
g as Autosave,
y as useAutosave,
D as useDebounce
};