reactjspersistencereact-hook-form

React Hook Form and persistent data on page reload


I'm using React Hook Form v7 and I'm trying to make my data form persistent on page reload. I read the official RHF documentation which suggests to use little state machine and I tried to implement it but without success. Is there a better way to do it? However...

The first problem I encountered using it, is that my data is a complex object so the updateAction it should be not that easy.

The second problem is that I don't know when and how to trigger the updateAction to save the data. Should I trigger it on input blur? On input change?

Here's my test code:

Edit busy-rgb-ljbo55


Solution

  • I already faced this issue and implemented it by creating a custom Hook called useLocalStorage. But since you are using the React hook form, it makes the code a bit complicated and not much clean!

    I suggest you simply use the light package react-hook-form-persist. The only work you need to do is to add useFormPersist hook after useForm hook. Done!

    import { useForm } from "react-hook-form";
    import useFormPersist from "react-hook-form-persist";
    
    const yourComponent = () => {
      const {
        register,
        control,
        watch,
        setValue,
        handleSubmit,
        reset
      } = useForm({
        defaultValues: initialValues
      });
    
      useFormPersist("form-name", { watch, setValue });
    
      return (
        <TextField
          title='title'
          type="text"
          label='label'
          {...register("input-field-name")}
        />
        ...
      );
    }