If we can't mutate states in React,
How should I do to update the state of an array of objects ?
const [data,setData] = useState(
[
{foo:'bar1',bar:'foo1'},
{foo:'bar2',bar:'foo2'},
{foo:'bar3',bar:'foo3'},
{foo:'bar4',bar:'foo4'}
]
);
useEffect(()=>{
const filterData = data => {
return data.map(item=>{
item.new='bluz'
return item
})
}
const updated = filterData([...data]);
console.log("OLD DATA",data);
console.log("NEW DATA",updated);
setData(updated);
},[])
The console logs two arrays of objects that all have the 'new' property set.
Using the spread operator [...data]
does not clone the different items.
So:
Do you confirm that I can't mutate the state like that, and that I should then deep clone my array ?
Is this the way to deep clone it ?
const clone = JSON.parse(JSON.stringify(data)); const updated = filterData(clone); setData(updated);