Dynamically Updating Data in React Charts
Describe the process for dynamically updating the data source of a React area chart, showing real-time stock market trends using TanStack React Charts.
import React, { useState, useEffect } from 'react';
import { Chart } from 'react-charts';
First, import React along with useState and useEffect for managing state and side effects, and the Chart component from react-charts.
function MyStockChart() {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
// Replace with your API call mechanism to fetch stock market data
const result = await fetch('https://api.example.com/stocks').then(res => res.json());
setData(result);
};
fetchData();
const interval = setInterval(fetchData, 60000); // Fetch new data every minute
return () => clearInterval(interval); // Cleanup on component unmount
}, []);
Define the MyStockChart component. Use useState to manage the chart data and useEffect to fetch the stock market data on mount. The fetchData function fetches data from an API and updates the state. Set an interval to fetch new data every minute for real-time updates.
const axes = React.useMemo(() => [
{ primary: true, type: 'time', position: 'bottom' },
{ type: 'linear', position: 'left' }
], []);
Configure the axes for the chart. The x-axis is a time scale (assuming your data includes timestamps), and the y-axis is linear, representing stock values.
return (
<div style={{ width: '400px', height: '300px' }}>
<Chart data={data} axes={axes} />
</div>
);
}
Render the Chart component within a div, passing the dynamically updating data and configured axes as props. The chart will automatically re-render when the data state updates.
export default MyStockChart;
Finally, export the MyStockChart component so it can be used in other parts of your application.