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

131
Visualizações
react function only sets variable on the second run

I am trying running a function after a click on a button. This function is fetching data from backend and stores the response data in a variable called (rows), running setRows(output), with output being formatted data from the response.

The issue is that in the first run, the rows variable is empty but the output variable is as it should be. After the second click on the button, everything seems fine, the rows are set. I would like to know what is causing this?

export default function Datatable() {

  const [rows, setRows] = useState({});

  async function fetchData() {

    let id = 0;
      
       const res = await fetch('/table/data).then(res => res.json());
       const data = res.results.bindings;

       const output = Object.keys(data).map(key => {          
        return {id: id++, opNr: data[key].opNr.value, opName: data[key].opName.value }; 
      })

      setRows(output);  

      console.log(output);
      console.log(rows);
  }
 return (<button type="button" class="a-button " onClick={fetchData}> </button>);
}
about 4 years ago · Juan Pablo Isaza
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