When I render this React component:
import React, { useState, useEffect, useCallback } from "react";
// import RenderLineChart from "../recharts/rechart.component";
import axios from "axios";
import "./chart-item.styles.scss";
const ChartItem = ({ apiUrl }) => {
const [chartData, setChartData] = useState([]);
//function that pulls data from APIs
const loadChartData = useCallback(() => {
axios.get(apiUrl).then((response) => {
setChartData(response.data);
});
}, [apiUrl]);
//runs initial pull from API
useEffect(() => {
loadChartData();
}, [loadChartData]);
console.log("Raw Data: ");
console.log(chartData);
console.log("Array: ");
console.log(chartData.historical);
// console.log("Array Element: ");
// console.log(chartData.historical[0]);
return <div className="chart"></div>;
};
export default ChartItem;
When I uncomment that third console.log statement and save the component file without refreshing localhost, the output is:
But when I actually refresh the localhost tab, the output is such:
As if it is no longer being treated as an array. Can anyone explain what's going on here?
chartData
is originally an empty array:useState([]);
, until data is loaded, which doesn't have.historical
, and you are trying to read.historical[0]
, hence the error.