Created
February 8, 2024 23:50
-
-
Save akullpp/02bb39970cf8edf9622617c25d3d39bb to your computer and use it in GitHub Desktop.
Autosave hook for react-hook-form
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 { useCallback } from 'react' | |
import { debounce } from 'lodash-es' | |
import { useWatch } from 'react-hook-form-mui' | |
import type { useForm } from 'react-hook-form-mui' | |
import { useDeepEffect } from '@/hooks/use-deep-effect' | |
const useAutoSave = (context: ReturnType<typeof useForm>, onSubmit: (data: unknown) => void) => { | |
const watch = useWatch({ control: context.control }) | |
const { dirtyFields } = context.formState | |
const hasDirtyFields = Object.keys(dirtyFields).length > 0 | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
const debouncedSave = useCallback( | |
debounce(() => { | |
context.handleSubmit(onSubmit)() | |
}, 500), | |
[], | |
) | |
useDeepEffect(() => { | |
if (hasDirtyFields) { | |
debouncedSave() | |
} | |
}, [watch]) | |
} | |
export { useAutoSave } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment