I try to load data in a graph using a rest api, but it doesn't load for some reason, can you help me
this is the data that the api brings { "avg_soc_fleet": 74.85 }
here is the code
const Rem = () => {
const [avgSoc, SetAvgSoc] = useState({});
useEffect(() => {
axios.get('http://127.0.0.1:8000/other/avgsoc_fleet').then(response => {
SetAvgSoc(response.data);
})
}, []);
const [avgChart] = useState({
labels: ['Soc', 'Pressure', 'Isolation', 'BattVolt24'],
datasets: [
{
data: [Object.values(avgSoc)],
fill: false,
borderColor: '#4bc0c0',
tension: .4
},
]
});
const options = {
legend: {
display: true,
}
};
return (
<div className="grid">
<div className="col-8">
<div className="card">
<Chart type="line" data={avgChart} options={options} />
</div>
</div>
</div>
);
};
export default Rem;
render chart I hope I can load the data from the api in the graph in react
CodePudding user response:
You need to update the avgChart after getting the response from axios. In that case avgSoc seems unnecessary, try the following:
const Rem = () => {
const [avgChart, setAvgChart] = useState();
useEffect(() => {
axios.get('http://127.0.0.1:8000/other/avgsoc_fleet').then(response => {
const chartOptions={
labels: ['Soc', 'Pressure', 'Isolation', 'BattVolt24'],
datasets: [
{
data: [Object.values(response.data)],
fill: false,
borderColor: '#4bc0c0',
tension: .4
},
]
}
setAvgChart(chartOptions);
})
}, []);
const options = {
legend: {
display: true,
}
};
return (
<div className="grid">
<div className="col-8">
<div className="card">
<Chart type="line" data={avgChart} options={options} />
</div>
</div>
</div>
);
};
export default Rem;
OBS: This is an example of how to proceed, not necessarily the only possible implementation.
CodePudding user response:
Once you get the data, you need to update the avgChart
again. use a setState method
const [avgChart, setAvgChart] = useState({
add new useEffect
useEffect(() => {
if(avgSoc.length){
setAvgChart({
...avgChart,
datasets: {
...avgChart.datasets
data: [Object.values(avgSoc)],
}
})
}
}, [avgSoc]);