I am receiving data from an API and I want to take that data and have it populate my chart. I can see where the API data is being called and is being passed into setState but I cannot seem to correctly take this data and pass it to my chart.
I have tried using the destroy() and update() methods for Chart.js to no avail. I'm sure it is just a matter of me not using them correctly within my app. The code below does not include those methods since I wasn't sure where to use them. I have also tried pushing the API data into the data array for the chart with no luck.
componentDidMount() {
// create chart
new Chart(myChartRef, {
type: "line",
data: {
labels: ["Jan", "Feb", "March"],
datasets: [
{
data: this.state.chartData,
backgroundColor: gradient,
pointBackgroundColor: "#fff",
pointBorderColor: gradient,
pointRadius: "5",
hoverBackgroundColor: "#75C6FF",
hoverBorderColor: gradient
}
]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [
{
gridLines: {
color: "#535356"
},
ticks: {
fontColor: "#87889C"
}
}
],
yAxes: [
{
gridLines: {
color: "#535356"
},
ticks: {
fontColor: "#87889C"
}
}
]
}
}
});
/* fetch API data and use it to set app state (setState) */
const getChartData = () => {
fetch(
"https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD"
)
.then(response => {
return response.json();
})
.then(myJson => {
const bitcoinPrice = myJson.BTC.USD;
this.setState({ chartData: bitcoinPrice });
console.log(JSON.stringify(myJson));
});
};
getChartData();
}
In the code I create a new chart once the component is mounted. Then I call the API and receive the data which I want to display on my chart. I can see in the React dev tools that the state is being set in my app but the chart does not update. I assume I need to do something like map the API data into the data array in the chart but I'm not sure how to do this properly and I have had no luck with the other solutions suggested on SO or anywhere else online.
This is my first React app so I'm not sure if I'm doing something wrong in React or in Chart.js?