Sometimes, we want to update an object in a React component state.
In this article, we’ll look at how to update an object in a React component state.
How to update an object in a React component state?
To update an object in a React component state, we can manipulate the state object with object spread.
For instance, we write:
import React, { useState } from "react";
const u = {
1: { id: 1, name: "John" },
2: { id: 2, name: "Jim" },
3: { id: 3, name: "James" }
};
export default function App() {
const [users, setUsers] = useState(u);
const addUser = () => {
setUsers((u) => {
return {
...u,
[Object.keys(u).length + 1]: {
id: Object.keys(u).length + 1,
name: "Mary"
}
};
});
};
return (
<>
<button onClick={addUser}>add user</button>
{Object.entries(users).map(([, val]) => {
const { id, name } = val;
return <p key={id}>{name}</p>;
})}
</>
);
}
We have the u object with some user data.
And we set u as the initial value of the users state.
Then we define the addUser function that calls setUsers with a function that returns an object with the new user entry with the key set to Object.keys(u).length + 1.
Object.keys(u) returns an array of object keys.
Then we set addUser as the value of the onClick prop of the button.
Finally, we render the entries in users with:
Object.entries(users).map(([, val]) => {
const { id, name } = val;
return <p key={id}>{name}</p>;
})
Now when we click add user, we see new entries displayed.
Conclusion
To update an object in a React component state, we can manipulate the state object with object spread.