Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!