How can we achieve automatic updating of chart data in a chart component wrapped with React?
For example, the data I requested from backend will change and I want to update it whever it changes.
I tried to look up the documents of some chart library, but didn’t find the answer.
2
Answers
If you are passing a state with data to a line chart or any other chart from
react-chartjs-2
, it gets automatically updated.Here is a basic example, hopefully, it makes sense for you.
Solution
In VChart, you can update the chart by calling either updateSpec or updateData.
To update the chart data, you can save the chart instance using ref when initializing the chart instance in a React component. Then, use useEffect to set the dependencies to the data that needs to be updated, and call the chart instance’s updateData method in the callback function.
VChart also provides a React-VChart wrapper:
https://www.visactor.io/vchart/guide/tutorial_docs/Cross-terminal_and_Developer_Ecology/react
You can refer to the code example below to update the chart data using React-VChart.
Code Example
Clicking the "Update the data of bar chart" button allows for the updating of the chart’s data.
Results
Online demo:https://codesandbox.io/s/visactor-vchart-react-demo-forked-jsqqjj
Related Documentation
react-vchart Tutorial:https://www.visactor.io/vchart/guide/tutorial_docs/Cross-terminal_and_Developer_Ecology/react
github:https://github.com/VisActor/VChart