Last active
May 6, 2024 23:46
-
-
Save layerok/d823dca699633277d46d89e43209da34 to your computer and use it in GitHub Desktop.
persist formik
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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