Reputation: 362
I was wondering about how to replace the item if it already exists inside state array and I got a great solution
https://codesandbox.io/s/4xl24j7r69
It works fine but my problem is I can't add a new item if the item doesn't exist inside the array I got an error Cannot convert undefined or null to object
Like this:
add = () => {
let newUser1 = {
"userId": 1,
"id": 3, // this is new id which is doesn't exist in this.state.data
"title": "Two New",
"body": "new data"
}
this.setState(prevState => {
let newData = prevState.data;
let user = newData.find(d => d.id === newUser1.id);
Object.assign(user, newUser1);
return { data: newData };
})
};
Upvotes: 0
Views: 1558
Reputation: 5748
You're not adding the newUser to the data on state.
add = () => {
let newUser1 = {
"userId": 1,
"id": 4,
"title": "Two New",
"body": "new data"
}
this.setState(prevState => {
const user = prevState.data.find(d => d.id === newUser1.id);
if (!!user) {
//Casting user to a boolean, if find did return a truthy value you add it to the data with map
Object.assign(user, newUser);
const newData = prevState.data.map(d => d.id === user.id ? user : d);
return { data: newData }
} else {
return { data: prevState.data.concat(newUser1)};
}
})
};
Upvotes: 1