Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda