Skip to content

Instantly share code, notes, and snippets.

@akullpp
Created February 8, 2024 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akullpp/02bb39970cf8edf9622617c25d3d39bb to your computer and use it in GitHub Desktop.
Save akullpp/02bb39970cf8edf9622617c25d3d39bb to your computer and use it in GitHub Desktop.
Autosave hook for react-hook-form
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