1

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:

  1. Do you confirm that I can't mutate the state like that, and that I should then deep clone my array ?

  2. Is this the way to deep clone it ?

    const clone = JSON.parse(JSON.stringify(data));
    const updated = filterData(clone);
    setData(updated);
    
gordie
  • 1,637
  • 3
  • 21
  • 41
  • For deep clone refer this https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript – Srimurugan Subramanian Jan 26 '22 at 10:40
  • When the code says: `item.new = 'bluz` each element in the array is being added a `new` prop. If the objective is to avoid this & instead only have this `new` prop on the resulting array, `filterData` should be like so: `const filterData = paramData => paramData.map(o => ({...o, o.new: 'bluz'});`. – jsN00b Jan 26 '22 at 10:59
  • Does this answer your question? [Update one of the objects in array, in an immutable way](https://stackoverflow.com/questions/43792457/update-one-of-the-objects-in-array-in-an-immutable-way) – Giorgi Moniava Jan 26 '22 at 11:14

1 Answers1

0

Yes, this is better you first assigned the state's array in a new array, then change your new array, then use setData(new array).

https://reactjs.org/tutorial/tutorial.html#why-immutability-is-important

e.g an image from the same reactjs.org:

enter image description here

Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20
  • I dont think so, for example with chat app with large paging data, each time load more a paging data, better we do not mutate new object and append new array data to it – famfamfam May 09 '23 at 09:37