I am trying to update a single key value pair in an array of objets using React.
Here is the setup
An array of objects
const array = [
{id:1,name:'Tyler',age:23},
{id:2,name:'Lauren',age:28},
{id:3,name:'Nico',age:14},
]
Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, {id:2,name:'Lauren',age:28} should change to {id:2,name:'Lauren',age:56}
My approach
I've set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.
This is what I currently have:
import { useState } from "react";
const array = [
{ id: 1, name: "Tyler", age: 23 },
{ id: 2, name: "Lauren", age: 28 },
{ id: 3, name: "Nico", age: 14 }
];
export default function App() {
const [list, setList] = useState(array);
const updateAge = (id = 2, age = 56) => {
setList([...list, list.filter((item) => item.id === id)]);
};
return (
<>
<ul>
{list.map((item) => {
return (
<li>
{item.name} | {item.age}
</li>
);
})}
</ul>
<button onClick={updateAge}>Update age</button>
</>
);
}
Here is my codesandbox link
mapinstead. When the id matches, return a new object with updated age, otherwise return the same object that the map function was called with.onChangein an array of object in React Hooks. Notice how the solution is the same as classes (and the one you accepted as well)?