Last active
November 26, 2023 23:47
-
-
Save caelinsutch/3b1a892c03714faebbf1d7f2a65e596b to your computer and use it in GitHub Desktop.
Save on Change for React Hook Form
This file contains hidden or 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 debounce from "debounce"; | |
import { useCallback } from "react"; | |
import { useWatch, type UseFormReturn, type FieldValues } from "react-hook-form"; | |
import useDeepCompareEffect from "use-deep-compare-effect"; | |
export const useSaveOnChange = <T extends FieldValues = FieldValues>( | |
form: UseFormReturn<T>, | |
onSubmit: (data: T) => void | |
) => { | |
const watchedData = useWatch({ | |
control: form.control, | |
}); | |
const debouncedSave = useCallback( | |
debounce(() => { | |
void form.handleSubmit(onSubmit)(); | |
}, 1000), | |
[] | |
); | |
useDeepCompareEffect(() => { | |
if (form.formState.isDirty) { | |
debouncedSave(); | |
} | |
}, [watchedData]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment