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

150
Views
How to get the setState reassigned in react

I can't get the setState to update to the new value in the code below.

I'm trying to get it to create a dynamic line graph using chart.js. I'm getting the correct data from the dummy API but I can't get it to state to my useState.

import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import axios from "axios";

function Graph(){
  const [chartData, setChartData] = useState([]);


  const chart = async () => {
    let empSal = [];
    let empAge = [];
    try {
      const res = await axios.get("http://dummy.restapiexample.com/api/v1/employees");
      for (const dataObj of res.data.data) {
        empSal.push(parseInt(dataObj.employee_salary));
        empAge.push(parseInt(dataObj.employee_age));
      }
      setChartData({
        labels: empAge,
        datasets: [
          {
            label: "level of thiccness",
            data: empSal,
            backgroundColor: ["rgba(75, 192, 192, 0.6)"],
            borderWidth: 4
          }
        ]
      });
      console.log(res.data)
    } catch (err) {
      console.error(err);
    }    
   
    console.log(empSal, empAge);
    console.log(chartData)
  };

  useEffect(() => {
    chart();
  }, [chartData]);
  return (
    <div className="App">
      <h1>Data Vis</h1>
      <Line data={chartData}/>
    </div >
  );
};
export default Graph;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Welcome to stackoverflow

  • The function should be moved into the useEffect.

https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1

  • Not sure why chartData is on the dependency array, doesn't it get an infinite loop? If you want the function to run only 1 time, you can change [chartData] to []

https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

about 4 years ago · Juan Pablo Isaza Report

0

I ended up finding the problem. The state was being updated correctly. I had the data formatted wrong within the data set so it wouldn't render anything on the page. I just had to remove the [] from around the background color line.

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!