I'm trying to read data from a CSV file and draw a React chart on the UI. I have the following code.
import Paper from "@material-ui/core/Paper";
import {ArgumentAxis, Chart, LineSeries, ValueAxis} from '@devexpress/dx-react-chart-material-ui';
const App = () => {
let data4 = []
ReadString().then(a => {
data4 = a
}).catch(e => {
console.log('e =>' e)
})
return (
<Paper>
<Chart data={data4}>
<ArgumentAxis/>
<ValueAxis/>
<LineSeries valueField="y" argumentField="x"/>
</Chart>
</Paper>
);}
Since the ReadString() is a Promise I can't directly assign the retuning array to Chart data={}. I was thinking when the data is available it will set data4 variable as I do the a=> data= a in the ReradString() function. It shows an empty chart. What is the issue with the code?
CodePudding user response:
The issue is data4
is just a local variable, not a state variable so updating the variable does not trigger page re-render.
To do it properly, you need to make data4
a state variable.
Also, calling the ReadString()
promise in the main function body will cause it to be called each time page re-renders. Instead, use useEffect
to call it only on page mount.
Something like this:
import { useEffect, useState } from 'react';
// ...
const [data4, setData4] = useState([]);
useEffect(() => {
// call `ReadString()` and set `data4` by calling `setData4`
}, []);
// ...