Skip to content

Instantly share code, notes, and snippets.

@layerok
Last active May 6, 2024 23:46
Show Gist options
  • Save layerok/d823dca699633277d46d89e43209da34 to your computer and use it in GitHub Desktop.
Save layerok/d823dca699633277d46d89e43209da34 to your computer and use it in GitHub Desktop.
persist formik
import { FormikValues, useFormik as useFormikBase } from "formik";
import { ChangeEvent, useCallback, useState } from "react";
export const usePersistFormik = <Values extends FormikValues = FormikValues>(
formik: ReturnType<typeof useFormikBase<Values>>,
opts: {
storageKey: string;
},
) => {
const { storageKey } = opts;
const [hydrated, setHydrated] = useState(false);
const clearStorage = useCallback(() => {
localStorage.removeItem(storageKey);
}, [storageKey]);
const handleChange = useCallback(
(e: ChangeEvent<any>) => {
localStorage.setItem(storageKey, JSON.stringify({
...formik.values,
[e.currentTarget.name]: e.currentTarget.value,
}));
formik.handleChange(e);
},
[formik, storageKey],
);
const hydrate = useCallback(() => {
const rawValues = localStorage.getItem(storageKey);
const values = rawValues ? JSON.parse(rawValues): null;
if (values) {
formik.setValues(
{
...formik.values,
...values,
},
false,
);
}
setHydrated(true);
}, [formik, setHydrated, storageKey]);
return {
...formik,
hydrated,
clearStorage,
hydrate,
handleChange,
handleCheckboxChange,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment