[Chartjs]-Setting dynamic state data in Chart.JS + React

0👍

The data is in datasets must be unified . For example all have to be numbers. but one exception is possible and that is null and undefined. because you are waiting for axios call to be resolved and this progress is asynchronous your data list will empty.

one solution is to fulfill your data in axios response and set a data state and change it there:

const BarChart = () => {
  const selected = useParams();
  const [data, setData] = useState({ labels: [], datasets: [] });
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    axios
      .get(`http://localhost:4040/profile/${selected.platform}/${selected.id}`)
      .then(res => {
        if (loaded === false) {
          //Bar Graph

          const data = {
            labels: [
              'Headshots',
              'Kills',
              'Shots Hit',
              'Shots Fired',
              'Snipers Killed',
            ],
            datasets: [
              {
                label: 'Player Statistics',
                data: [
                  res.data.segments[0].stats.headshots.displayValue,
                  res.data.segments[0].stats.kills.displayValue,
                  res.data.segments[0].stats.shotsHit.displayValue,
                  res.data.segments[0].stats.shotsFired.displayValue,
                  res.data.segments[0].stats.snipersKilled.displayValue,
                ],
                backgroundColor: [
                  'rgba(255, 99, 132, 0.6)',
                  'rgba(54, 162, 235, 0.6)',
                  'rgba(255, 206, 86, 0.6)',
                  'rgba(75, 192, 192, 0.6)',
                  'rgba(153, 102, 255, 0.6)',
                ],
              },
            ],
          };
          setLoaded(true);
          setData(data);
        }
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  if (loaded === false) {
    return loaded;
  } else {
    return (
      <div className='chart'>
        {data && (
          <Bar
            redraw
            data={data}
            width={350}
            height={350}
            options={{
              maintainAspectRatio: true,
            }}
          />
        )}
      </div>
    );
  }
};

export default BarChart;

Leave a comment