Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda