I have an array of objects in the state with the following structure:
const arrayOfTests = [
{
id: 1,
name: "test1",
description: "test description"
},
{
id: 2,
name: "test2",
description: "test description"
},
{
id: 3,
name: "test3",
description: "test description"
}
]
Lets say I find object with id of 3 like this:
let object3 = arrayOfTests.find((element) => {
return element.id === 3;
})
And then I edit it like this:
object3.description = "new description"
I'm kinda confused how to use setState to replace/edit the old object 3, with the new updated one.
Use the map() method as shown below.
Inside the callback function, check if the condition element.id === 3 is true; if it is, return a new object. Otherwise, return the current element as it is.
let newState = arrayOfTests.map((element) => {
if (element.id === 3) {
return { ...element, description: "new description" };
}
return element;
});
Pass the array returned by the map() method to the state setter function.
this.setState({ state: newState });
setState((prevState) => ({
...prevState,
arrayOfTests: prevState.arrayOfTests.map((item) =>
item.id === 3 ? { ...item, description: "new description" } : item
),
}));
this.setState({
arrayOfTests: arrayOfTests.map(item => {
if (item.id === 3) {
return {
...item,
description: 'new description'
}
}
return item
})
})