Skip to content

issue: setValue() doesn't update the state of multiple checkbox values (arrays)  #12316

@matmannion

Description

@matmannion

Version Number

7.53.0

Codesandbox/Expo snack

https://codesandbox.io/s/eager-sun-jt4df?file=/package.json

Steps to reproduce

  1. Create a form with a nested multi-checkbox type, e.g.
      <form onSubmit={handleSubmit(onSubmit)}>
        <label className="label"><input {...register("fields.checkbox")} type="checkbox" name="checkbox" value="1" /> Checkbox one</label>
        <label className="label"><input {...register("fields.checkbox")} type="checkbox" name="checkbox" value="2" /> Checkbox two</label>
        <label className="label"><input {...register("fields.checkbox")} type="checkbox" name="checkbox" value="3" /> Checkbox three</label>
        <label className="label"><input {...register("fields.checkbox")} type="checkbox" name="checkbox" value="4" /> Checkbox four</label>
        <button type="button" onClick={() => setValue("fields", { checkbox: ['1', '3'] })}>Check odd numbers</button>
        <input type="submit" />
      </form>

Click the button to call setValue with the checkbox fields nested inside.

Expected behaviour

The checkboxes should be checked. The internal value is updated, but the actual form state isn't updated because in setValue we call setValues instead of setFieldValue if the value isn't primitive - this looks like it was only intended to cover plain objects but it also catches arrays. This means that RHF tries to setFieldValue on fields.checkbox.0 (etc) which won't have a matching _fields ref.

What browsers are you seeing the problem on?

No response

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions