Categories
React Answers

How to update a state when state is an array of objects with React?

Spread the love

Sometimes, we want to update a state when state is an array of objects with React.

In this article, we’ll look at how to update a state when state is an array of objects with React.

How to update a state when state is an array of objects with React?

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.

For instance, we write:

import React, { useState } from "react";

const items = [
  { id: 1, num: 1 },
  { id: 2, num: 2 },
  { id: 3, num: 3 }
];

export default function App() {
  const [vals, setVals] = useState(items);
  const onClick = () => {
    setVals((vals) => {
      return [
        ...vals.slice(0, 1),
        { id: 2, num: Math.random() * 100 },
        ...vals.slice(2)
      ];
    });
  };

  return (
    <div>
      <button onClick={onClick}>update</button>
      {vals.map((v) => {
        return <p key={v.id}>{v.num}</p>;
      })}
    </div>
  );
}

We define the vals state with the useState hook.

Then we define the onClick function that calls setVals with a callback that takes the existing vals array value as the parameter.

And then we return the new value for the vals state by updating the 2nd entry of it and keeping the rest the same.

We spread the existing elements returned by slice and only change the num property of the 2nd entry.

Finally, we set the onClick prop of the button to onClick so vals is updated when we click it.

And we render the num in vals with vals.map.

Conclusion

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to update a state when state is an array of objects with React?”

this article was so helpful! i have been dying to find a tutorial that teaches how to update an array of objects in reactjs! thank you so much!

Leave a Reply

Your email address will not be published. Required fields are marked *