Home > Mobile >  Why am I mutating the original array with filter method? [React]
Why am I mutating the original array with filter method? [React]

Time:12-06

After executing the newData[0].id = newValue I am actually updating the react initialData state. How is that possible?

Is my understanding that filter should return a new array different than the original one, also I am not ussing the setState feature so I don't understand why the state is changing.

enter image description here

CodePudding user response:

Because arrays are mutable. it will keep the reference to the original array even after filtering.

use the spread operator to avoid mutating the original array

const data = [...newData]
data[0].id = newValue

CodePudding user response:

As per the new beta docs on updating items in array

setInitialData(prev => {
 // create a new array
 const withReplaced = prev.map(elem => {

    if (elem.id === id) {
        const newVal = //set new value
        // create a new updated element
        return {
          ...elem,
          id: newVal
        }
      } else {
        // The rest haven't changed
        return elem;
      }

  });

 return  withReplaced;

})

Hope it helps

CodePudding user response:

you can't update the initialData,but the you can update the son of the array.And if you don't use "setData".The views won't change.

  • Related