Home > Enterprise >  Updating a specific field of object state in React
Updating a specific field of object state in React

Time:04-05

I am using a React functional component where I want to update only a specific field of the state and retain the other values like before. Here's the state initialization -

const[value, setValue] = React.useState({
     a: "5",
     b: "6"
});

I wish to only update value of 'a' to something else, let's say 7 (whilst retaining the same value for 'b'). Currently I am doing this -

setValue(currValue => ({
   ...currValue,
   a: "7"
}))

Is this wrong ? If yes, what's the correct way of doing it ?

CodePudding user response:

What you are doing is correct.

That's the proper way for updating the state based on the current value of the state. It's called the functional form of the setState call.

setState((prevState) => {
  // Do something with prevState
  return newState; // Be aware to not mutate the prevState directly
});

Examples:

// Array

setState((prevState) => {
  const newState = Array.from(prevState);
  newState.push('foo');
  return newState;
});

// Object

setState((prevState) => {
  return({
    ...prevState,
    foo: 'bar'
  });
});

The main think is that the object/array reference needs to change!

  • Related