How to get the setState reassigned in react

Viewed 59

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;
2 Answers

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.

Related