Chartjs-Cannot access before initialization React Error

0๐Ÿ‘

  • you can keep the initial state as undefined (by default if nothing is provided)

  • Make the structure you want before setting it to state from the API response ( I am not sure of the response structure but you can make it as you need)

  • Added a loading state till the response is available (for demo purpose).

    function App() {
        const [chartjs, setChartjs] = useState();
    
        const url =
          "https://datausa.io/api/data?drilldowns=Nation&measures=Population";
    
        useEffect(() => {
          axios.get(url).then((response) => {
            const data = {
              labels: response.data.data.map((item) => item.Year),
              datasets: [
                {
                  labels: "Population",
                  data: response.data.data.map((item) => item.Population),
                },
              ],
            };
            setChartjs(data);
          });
        }, [url]);
    
        if(!chartjs) return "loading ...."
    
        return (
          <div>
            <BarChart chartData={chartjs} />
          </div>
        );
    }
    

Leave a comment