javascriptarraysclonespread-syntax

Can't separate array of object in state using ... operator or Array.from() or or slice(0),,Javascript/React


this is my state

state = {
 size: window.innerWidth <= 700 ? (window.innerWidth <= 425 ? 200 : 300) : 400,
 positions: [
   { row: 2, col: 5, value: 2, id: 1 },
   { row: 3, col: 2, value: 2, id: 2 },
 ],
}

this is what i am doing

//let oldPosition = Array.from(this.state.positions);  //1 method
//let oldPosition = [...this.state.positions];         //2 method
let oldPosition = this.state.positions.slice(0);       //3 method
oldPosition[1].value = 14;

whatever i do among 3 methods i can't prevent the changing of the state

i am trying to make copy of positions and store it in oldPosition but on changing any value from the oldPosition i somehow change the orignal state of my app :(

Appreciate your Help.


Solution

  • In order to clone your array of objects you can create a new array by mapping over the state array and returning each object with a spread.

    let oldPosition = this.state.positions.map(pos => ({...pos}));