Home > Back-end >  Unregistering nested property deletes the whole object
Unregistering nested property deletes the whole object

Time:10-08

I created a sandbox of my react-hook-form demo.

You'll notice all my fields are virtual, there is no input component for them:

const form = useForm({
  defaultValues: {
    groups: {}
  }
});

So you see my default values start at: { groups: {} }.

I am able to successfully add a group like this:

form.register(`groups.${groupId}`);
form.setValue(`groups.${groupId}`, { name: "foo" });

Doing this is good, I expect this behavior, it makes my values now: { groups: { [groupId]: { name: 'foo' } }

However when I try to delete with:

form.unregister(`groups.${groupId}`)

It deletes the entire groups object. My values unexpectedly is now {}. I was expecting it to be { groups: {} }.

Any ideas?

CodePudding user response:

RHF will remove the whole object if you unregister the last property inside it:

// {
//   groups: {
//     Group1: { ... },
//     Group2: { ... },
//   }
// }


form.unregister(`groups.Group2`);
// {
//   groups: {
//     Group1: { ... },
//   }
// }

form.unregister(`groups.Group1`);
// {}

I had a look at the unregister method and there are no options to retain the object shape if it's empty inside. A workaround is simply create a dummy field:

const form = useForm({
  defaultValues: {
    groups: {
      _: ""
    }
  }
});

And make it unregisterable:

Object.entries(groups)
  .filter((g) => g[0] !== "_")
  .map(([groupId, group]) => (
    <div key={groupId}>
      <h4>Group ID: {groupId}</h4>
      <DeleteGroupButton groupId={groupId} />
    </div>
  ));
  • Related