react-hook-form: setValue not working for arrays with controller

Describe the bug I wonder if this bug is related to https://github.com/react-hook-form/react-hook-form/issues/5232 as the issues I usually see are related to non-primitive values, namely arrays.

To Reproduce

  1. Use controller interface instead of register to track fields in your form
  2. Add a manually tracked field via defaultValues
  3. Add a callback modifying the manual field and call it (in my example by pressing the “Remove” button)
  4. Press the “submit” button

Codesandbox link (Required) https://codesandbox.io/s/dark-voice-glnie?file=/src/App.tsx

Expected behavior The submitted values are

{
  "array": ["a"],
  "firstName": "alll"
}

Actual behavior The submitted values are

{
  "array": ["a", "b"],
  "firstName": "alll"
}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (3 by maintainers)

Most upvoted comments

@mrlubos I trimmed it down to this repro here: https://codesandbox.io/s/react-hook-form-react-select-u36uv

It’s actually not behaving like the real app where I see always an empty array but I see another weird behaviour. Removing all items from the select… 🤔

  • leaves 1 item in the watched values
  • is undefined in submit values

@damianobarbati Are you able to upgrade react-select to version 4.0.0 or newer? Doing so fixes the issues you mention above. Can you verify if that would also resolve the other issues you’re seeing?

@mrlubos I see it working properly with the latest react-select. I’ll ping if I manage to reproduce the real app behaviour, thank you!

@mrlubos thanks, I tried both on 7.8.8 and the 7.9.0 but I can’t manage to have the array properly working, only defaultValues is always passed from Controller to react-select.

I’m sticking to this workaround of key={Date.now()} thus always re-rendering the component wrapping the react-select into <Controller />.

Thanks!

If you share a CodeSandbox we might be able to help you @damianobarbati

Are you still using:

useEffect(() => {
  register('array')
}, []);

where you have an array field?

@damianobarbati As of version 7.8.8, I define the form like this.

const { register } = useForm({
  defaultValues: {
    array: [],
  },
  shouldUnregister: true,
});

And in the same component I also add this hook.

useEffect(() => {
  register('array');
}, [register]);

Hopefully this helps!

I would register that key as input, so hook form knows it’s a group input instead of individual inputs.

register('array') // you can do that in useEffect 

setValue('array', ['1', '2', '3']

Thanks @bluebill1049, I’ll have a look. Doing this triggers the other bug I reported in #5232 but I have not been able to reproduce it in CodeSandbox so far. Will keep you posted if I succeed