I am trying to update a react-chartjs-2 plot passing the new fetch date as props from the App.js to the Chart.js component.
I have created a button, that is linked to a function that calls for a useState in the main app.
Currently I have created two datasets 'data2' and 'data3', and the button should update the plot with the data from 'data3. However whenever I click the button, instead of updating the plot it simply goes blank.
I have the feeling that I am not using the right approach to update the plots but I do not find a lot of information about it.
Chart.js
import { Line } from 'react-chartjs-2';
const Chart = ({ data, options, onUpdate }) => {
const onClick = (e) => {
e.preventDefault()
onUpdate()
console.log(data)
}
const dataIn = data[0];
const optionsIn = options[0];
return(
<>
<div className='header'>
<h1 className='title'>Plot</h1>
<div className='links'>
<a
className='btn btn-gh'
onClick = {onClick}
>
Update plot
</a>
</div>
</div>
<Line data={dataIn} options={optionsIn} />
</>
)
}
export default Chart;
App.js
import { useState, useEffect } from 'react'
import Chart from './components/Chart'
function App() {
const data2 = {
labels: ['1', '2', '3', '4', '5', '6'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
fill: false,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgba(255, 99, 132, 0.2)',
},
],
};
const data3 = {
labels: ['1', '2', '3', '4', '5', '6'],
datasets: [
{
label: '# of Votes',
data: [3, 2, 5, 3, 19, 12],
fill: false,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgba(255, 99, 132, 0.2)',
},
],
};
const options2 = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
const [data, setData] = useState([
data2
])
const [options, setOptions] = useState([
options2
])
const updatePlot = () => {
setData(data3)
setOptions(options2)
}
return (
<div class="row">
<Chart data={data} options={options} onUpdate={updatePlot} />
</div>
);
}
export default App;