I am trying to update a value from an array object and object. my sample code is below. Not getting the result as I expected. It would be nice if someone can help?
let array = [
{
id:"01",
"name": {
"value": "jaison",
"error": null
},
"email": {
"value": "[email protected]",
"error": null
}
},
{
id:"02",
"name": {
"value": "jaison 1",
"error": null
},
"email": {
"value": "[email protected]",
"error": null
}
}
];
this.state{
data:array
}
//This two data getting a from a form
const key = "02";
const editedData = {name:"updated jaison 1", email:"[email protected]"}
const newData = [...this.state.data];
const index = newData.findIndex(item => key === item.id);
let item = newData[index];
//Working as expcted
console.log('1', item);
Object.keys(editedData).forEach(function (key) {
item[key] = editedData[key];
});
//Working as expcted
console.log('2', item);
this.setState({ data: [...this.state.data, item]}, () => {
//Not Working as expcted
console.log(this.state.data);
});
Expected result
let array = [
{
id:"01",
"name": {
"value": "jaison",
"error": null
},
"email": {
"value": "[email protected]",
"error": null
}
},
{
id:"02",
"name": {
"value": "updated jaison 1",
"error": null
},
"email": {
"value": "[email protected]",
"error": null
}
}
];
editedDatawhich is unused.