react-final-form-hooks icon indicating copy to clipboard operation
react-final-form-hooks copied to clipboard

Using initialValues with nested object causes infinite re-renders

Open bhuvanmehra opened this issue 6 years ago • 4 comments
trafficstars

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

Using a nested JSON object in initialValues causes infinite re-renders. Also, form fields can't be changed.

Steps-

  1. Open the code sandbox link
  2. Try to change the first name and last name fields
  3. Open console to see the infinite re-render console log messages

Example -

const Test = () => {
  const { form, handleSubmit, values, pristine, submitting } = useForm({
    onSubmit,
    validate,
    initialValues: {
      name: {
        firstName: 'Clark',
        lastName: 'Kent',
      }
    }
  });

What is the expected behavior?

Form should render once with initial values. And we should be able to update form field values.

Sandbox Link

https://codesandbox.io/s/cold-https-6v26o

What's your environment?

node: v10.2.1 react-final-form-hooks: "2.0.0", Mac OS Mojave 10.14.2

Other information

Screenshot Screen Shot 2019-06-27 at 5 35 16 pm

bhuvanmehra avatar Jun 27 '19 07:06 bhuvanmehra

I think that we could initialize value after react rendering, that means should set initial value on useEffect, in this case, a temporary solution is:

useEffect(() => {
  form.initialize({
    name: {
      firstName: 'Clark',
      lastName: 'Kent',
    }
  });
}, []);

linyanm avatar Jul 28 '19 16:07 linyanm

Thanks @l1nyanm1ng

bhuvanmehra avatar Jul 29 '19 00:07 bhuvanmehra

For future visitors to this issue, you can also use useMemo to make sure the object reference stays the same

const initialValues = useMemo(() => ({
  name: {
      firstName: 'Clark',
      lastName: 'Kent',
    }
}), [])
const Test = () => {
  const { form, handleSubmit, values, pristine, submitting } = useForm({
    initialValues
  });
}

Jephuff avatar Feb 04 '20 16:02 Jephuff

Thanks @Jephuff for the work around.

bhuvanmehra avatar Mar 18 '20 03:03 bhuvanmehra