Trying to use chart.js, but everytime i try fetch the data it throws me ‘Uncaught runtime errors:
ERROR
dispatcher is null’ this error. The page doesn’t render at all, everything on there is gone, before i tried to use chart.js i had a list of the data i wanted to put into the graph.
I have tried uninstalling and reinstalling chart.js, react-router-dom etc. and still the problem persists. I’m not sure whether or not this is an issue with my code or something to do with my environment. Any suggestions would be a massive help. Thank you. This is my file where the error may be.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
// Register Chart.js components
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);
function Security() {
const { id } = useParams();
const [security, setSecurity] = useState(null);
const [priceHistories, setPriceHistories] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const securityResponse = await axios.get(`http://localhost:5000/securities/${id}`);
setSecurity(securityResponse.data.security);
const priceHistoriesResponse = await axios.get(`http://localhost:5000/securities/${id}/price-histories`);
if (Array.isArray(priceHistoriesResponse.data)) {
const formattedPriceHistories = priceHistoriesResponse.data.map(history => {
const date = new Date(history[1]);
if (isNaN(date)) {
return { date: history[1], price: history[2] };
}
return { date: date.toISOString().split('T')[0], price: history[2] };
});
setPriceHistories(formattedPriceHistories);
}
} catch (error) {
console.error( error);
}
};
fetchData();
}, [id]);
const chartData = {
labels: priceHistories.map(history => history.date),
datasets: [
{
label: 'Price History',
data: priceHistories.map(history => history.price),
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
fill: false,
},
],
};
const chartOptions = {
responsive: true,
plugins: {
legend: {
position: 'top',
},
tooltip: {
callbacks: {
label: function(tooltipItem) {
return `Price: $${tooltipItem.raw}`;
}
}
}
},
scales: {
x: {
title: {
display: true,
text: 'Date',
},
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'll',
},
},
y: {
title: {
display: true,
text: 'Price ($)',
},
},
},
};
if (!security) {
return <div>Loading...</div>;
}
return (
<div>
<h1 className='security-header'>Price History for {security[1]}</h1>
<Line data={chartData} options={chartOptions} />
<table>
<thead>
<tr>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{priceHistories.map((history, index) => (
<tr key={index}>
<td>{history.date}</td>
<td>{history.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Security;