I have an array of objects that is being built through the UI. Let’s say each object is displayed as a card. I am also giving the user the ability edit each object (card). I am thinking the best way to update the array is based on the previous state.
This is what I have, but it is overwriting all objects in the array with the updated object
interface MyInterface {
cost: number;
name: string;
title: string;
id: string;
}
const [myObject, setMyObject] = useState<MyInterface[]>([]);
const handleUpdate = () => {
const updatedData = [
{
cost: updatedCost,
name: updatedName,
title: updatedTitle,
id: id,
},
];
const newList = myObject.map(card => {
if ((card.id = id)) {
return { ...card, updatedData };
}
return card;
});
setMyObject(newList);
}
handleUpdate
is called when the update button is clicked