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

265
Views
React - State is not updating when it is supposed to, why is react doing this? (not retaining)

Hi so I'm trying to grab some json from an api and then populate a table, pretty simple stuff. What's happening is that I can see the "tableData" state being updated as each new row comes in, I'm also logging every time "tableData" is updated, yet maybe .5 seconds after its all done my "tableData" is empty again (check console screenshots)

enter image description here

const [bigChartData, setbigChartData] = React.useState("data1");
  const [tableData, setTableData] = React.useState([]);

  const setBgChartData = (name) => {
    setbigChartData(name);
  };

  const getData = () => {
    axios.get("URL")
      .then(res => {
        const data = res.data.items.forEach(item => {
          setTableData(oldData => [...oldData, {
            data: [
              { text: item.title },
              { text: "asd" + item.url },
              { text: "some links..." }
            ]
          }]);
        });
      })
      .catch(err => console.log(err));

    setTimeout(function () {
      console.log(tableData);
    }, 3000);
  }

  useEffect(() => {
    getData();
  }, []);


  useEffect(() => {
    console.log("Table data updated:");
    console.log(tableData);
  }, [tableData]);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think you should not iterate through each row inside getData() method instead try following code

const getData = () => {
    axios.get("URL")
      .then(res => {
        const data = res.data.items.map(item => {
                return{
                       data: [
                          { text: item.title },
                          { text: "asd" + item.url },
                          { text: "some links..." }
                      ]
                };
          });

          setTableData(data) 

      }).catch(err => console.log(err));
   
}

or if you have already some data in tableData then

 setTableData([...tableData, data])
about 4 years ago · Juan Pablo Isaza Report
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!