Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda