I have an array of objects in my react state.
[
{
id: 'd8t4gf',
title: 'Working on',
items: [{ title: 'Item 1' }, { title: 'Item 2' }, { title: 'Item 3' }],
},
{
id: '8jy8g',
title: 'Done',
items: [{ title: 'Item 1' }, { title: 'Item 2' }],
},
]
I'm trying to update the items of the second object like so.
const handleAddNewItemSubmit = (title, id) => {
const listIndex = lists.findIndex((list) => list.id === id);
const newData = [...lists];
newData[listIndex].items = [...newData[listIndex].items, { title }];
setLists(newData);
};
Is there a better way to do this?
You're mutating the existing state (specifically, an array object - eg lists[0]
), which should never be done in React. What you're doing may happen to work, but it's not a good way.
Try something like this instead, cloning everything along the way down to the nested items
property:
const handleAddNewItemSubmit = (title, id) => {
setLists(
lists.map(list => list.id !== id ? list : ({
...list,
items: [...list.items, { title }]
})
);
};