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 };
})
};
Object.assign(user, newUser1);toObject.assign({}, user, newUser1);