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

103
Visualizações
How to add values from state to array in react app?

I am tring to push new value to arrays but the arrays is not updating with new values. It only contains one value after push. The arr value after button click only showing one value, but I want it to have multiple values. What are multiple ways to put values into arr variable or copy value to another variable?

function App() {
  const [value, setValue] = useState(null);
  let arr = [];

  function addToArr() {
     console.log(value);
     arr.push(value);

     console.log(arr);   // it is only showing one value
  }

  return (
    <div>react app
      <div>
          <textarea
            value={value}
            onChange={(e) => setValue(e.target.value)}
          >
          </textarea>

        <button onClick={addToArr}>Add</button>
      </div>
    </div>
 );
}

export default App;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your problem is you put let arr = []; in the component App which will be re-rendered whenever the state changes, your arr will be reset as well.

One possible fix could be moving your arr declaration out of the component App

let arr = []; //move it to the global scope
function App() {
  const [value, setValue] = useState(null);

  function addToArr() {
     console.log(value);
     arr.push(value);

     console.log(arr); 
  }

  return (
    <div>react app
      <div>
          <textarea
            value={value}
            onChange={(e) => setValue(e.target.value)}
          >
          </textarea>

        <button onClick={addToArr}>Add</button>
      </div>
    </div>
 );
}

export default App;

If you want to keep arr internally, you can use useRef which only refers to the same object during re-renderings

import React, { useRef, useState } from 'react'
function App() {
  const [value, setValue] = useState(null);
  const arrRef = useRef([]);

  function addToArr() {
     console.log(value);
     arrRef.current.push(value);

     console.log(arrRef.current);  
  }

  return (
    <div>react app
      <div>
          <textarea
            value={value}
            onChange={(e) => setValue(e.target.value)}
          >
          </textarea>

        <button onClick={addToArr}>Add</button>
      </div>
    </div>
 );
}

export default App;
about 4 years ago · Juan Pablo Isaza Relatório

0

For this you have 2 ways:

  1. Lifting arr variable before component
let arr = [];
function App() {
  const [value, setValue] = useState(null);
  ...
}
export default App;
  1. Using a new state
function App() {  
  ...
  const [newArrValue, setnewArrValue] = useState([]);

  const addToArr = () => {
    ...    
    newArrValue.push(value);
    setnewArrValue(newArrValue);
    console.log(newArrValue); 
  };
  ...
}
export default App;
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