Home > database >  Update only an object from another object and keep the rest of parameters the same
Update only an object from another object and keep the rest of parameters the same

Time:09-28

I have a structure like the following:

{
    firstname: '',
    company: {id: '', name: ''},
    nextAction: { by: '',
                  type: {id: '', name: ''}
                }
}

And the following functions to update the parameters ':

const handleInputValue = (e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;

if (name === 'firstName') {
  setValues({
    ...values,
    [name]: value,
  });
  validate({ [name]: value });
} else if (name === 'company') {
  setValues({
    ...values,
    [name]: { name: name, id: value },
  });
  validate({ [name]: value });
} else if (name === 'nextAction') {
  setValues({
    ...values,
    nextAction: { ...nextAction, value: { name: name, id: value } },
  });
  validate({ [name]: value });
}

It works to update 'firstname' and 'company' and I want to update only the 'type' for the 'nextAction' and keep the initial value for 'by' but I think the syntax is wrong. Any ideas?

Thank you!

CodePudding user response:

else if (name === 'nextAction') { setValues({ ...values, nextAction: { ...values.nextAction, value: { name: name, id: value } }, }); validate({ [name]: value }); }

You can spread the values by using ...values.nextAction

  • Related