useImmer dynamically modify WritableDraft properties

Viewed 19

I'm trying to modify the initialised value of person from useImmer using its updator function as below.

  type Person = {
    name?: string;
    age?: number;
    // lots of other optional properties
  };

  const [person, updatePerson] = useImmer<Person>({
    name: 'Michel',
    age: 33,
    // values for all other properties
  });

  function replacePerson(person: Person) {
    updatePerson((draft) => {
      Object.entries(person).map(([property, value]) => {
        draft[property] = value;
      });
    });
  }

The problem I have is that when I try to modify this person with my provided person, the provided person can have different properties so I am trying to do it using Object.entries as above however it seems draft[property] doesn't seem to work.

I know I could do it using draft.name = person.name and the same for the rest of the properties however I'm trying to do it dynamically as the provided person can have different properties.

0 Answers
Related