I have the following state:
[
[{ id: 2, valid: true, name: "b", visible: true }],
[{ id: 1, valid: true, name: "a", visible: false },
{ id: 3, valid: false, name: "c", visible: false }]
]
I use one Component to render each element of these arrays.
Users can edit the items, in this Component.
To achieve that I first shallow copy the Item and then update the attribute of the Item that was changed. See code:
export default function Item({item, updateItem}) {
function update(key, val){
let new_item = { ...item };
new_item[key] = val;
updateItem(new_item)
}
....
In the App Component i then update the actual state:
function updateItem(newItem){
setItems((sourceList) => {
let tempList = [...sourceList];
tempList.forEach((elements) => {
elements.forEach((item, idx) => {
if(item.id == newItem.id){
elements[idx] = newItem
}
})
});
return tempList;
})
}
Is this a valid way of doing it, or is this bad way? How would you update the State of this complex items array?