Chartjs-React using fetch returns undefined until save

0👍

There are a couple issues that need sorting out here. First, you can’t pass an async function directly to the useEffect hook. Instead, define the async function inside the hook’s callback and call it immediately.

Next, chartData is entirely derived from the apiCall, so you can make that derived rather than being its own state variable.

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

const Piegraph = () => {
  const [apiValue, setApiValue] = useState([]);

  useEffect(() => {
    async function loadData() {
      const response = await fetch(
        "https://api.spacexdata.com/v4/launches/past"
      );
      const data = await response.json();
      const item = data.results;
      setApiValue(item);
    }
    loadData();
  }, []);

  const success = apiValue.filter((v) => v.success);
  const failure = apiValue.filter((v) => !v.success);

  const chartSuccess = success.length;
  const chartFail = failure.length;

  const chartData = {
    labels: ["Success", "Fail"],
    datasets: [
      {
        label: "Space X Launch Statistics",
        data: [chartSuccess, chartFail],
        backgroundColor: ["rgba(75,192,192,0.6)"],
        borderWidth: 4,
      },
    ],
  };

  return (
    <div className="chart_item">
      <Pie data={chartData} />
    </div>
  );
};

export default Piegraph;

0👍

pull your chart algorithm outside or send item in. Like this

  useEffect(async() => {
    ...
    // everything is good here
    chart(item)
  })

you might wonder why I need to send it in. Because inside useEffect, your apiValue isn’t updated to the new value yet.

And if you put the console.log outside of chart().

  console.log(apiData)
  const chart = () => {
  }

you’ll get the value to be latest 🙂 amazing ?

A quick explanation is that, the Piegraph is called whenever a state is updated. But this update happens a bit late in the next cycle. So the value won’t be latest within useEffect.

Leave a comment