Home > Blockchain >  React.js - How to change object value inside array of objects
React.js - How to change object value inside array of objects

Time:02-05

i have a problem with array of objects which is inside state. My question is how to change an object value like in example code bellow

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "circle" }
    ]);

what i want is

[
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
]

so in short i just want to update array of objects by changing only this specific value

CodePudding user response:

setTheArrayOfObjects([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
  ]
)

While this might not be exactly what you asked it fits your needs and it is simple. Further complications like iterating through each element and finding pattern to reach specific element might end up with unexpected outputs.

If you don't like this, then you might come up with different state structure (an object instead of an array).

CodePudding user response:

Use a functional state update to correctly update from any previous state value. Shallow copy any parts of state that you are updating. Remember that the useState state updater function doesn't shallow merge your updates, you are returning an entire new state value.

Given:

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
  { color: "blue", shape: "square" }, 
  { color: "red", shape: "circle" }
]);

Update as follows:

  • Map the previous array to a new array reference
  • Shallow copy the array element you want to update, appending the updated properties

Example:

const updateShape = (shape, index) => {
  setTheArrayOfObjects(state => state.map((el, i) => i === index
    ? { ...el, shape }
    : el,
   ));
};

...

updateShape("rectangle", 1);

Helpful

Even though it's from Redux, the Immutable Update Patterns documentation is incredibly helpful in explaining in more detail what I described above and is still applicable to standard React state updates. Please do a read though.

  •  Tags:  
  • Related