Skip to content
Advertisement

React Hooks useState array storage problem

I have the following problem: I have a method that returns a multidimensional array in my Grids component. I would want to store any multidimensional array recomputed in a separate list. The problem is that when I am using my useState() declared in this way

const [listGrid,setListGrid] = useState<any[]>([])  

only the current state element is saved repeatedly in the array list. Follow the code of interest part :

const [listGrid,setListGrid] = useState<any[]>([]);
const grid= initGrid(); //initialise a new grid.
 const disableButtonHandler = ():void => {
       const cloneGrid =[...grid]
      console.log(cloneGrid===grid)//are no the same!!
      setListGrid(prevListGrid=>[...prevListGrid,cloneGrid]);
};

this is the snapshot of my list with the grids saved:

enter image description here

so, basically, all the arrays stored in listGrid are the same and I’d want to store any change of my computed list.

what could I do wrong with it? thanks in advance.

Advertisement

Answer

The matrix is represented by an array of arrays, while you are duplicating the containing array, the contained ones are still the same. Basically, cloneGrid[i] === grid[i] is true for 0 <= i < grid.length.

You can solve this by doing the following:

const cloneGrid = grid.map(row => [...row]);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement