Async data
Async data with surf-charts components
Handling Asynchronous Data
When working with dynamic data, especially in real-world applications, you often need to fetch data asynchronously from an API. Component from surf-charts can easily integrate with a lot of tools to handle such scenarios.
Tip
You can use any tool for async data with surf-charts.
But for better experience working with async data in surf-charts we recommend using TanstackQuery or SWR.
Next, we will analyze an example of loading asynchronous data using TanstackQuery
Async Data with React Query
Let's imagine that the chart data is lying on the server and we need to query it. We want to display in the chart container the statuses: download and error. And also show the data when it arrives. Let's create such component:
Example
import { useQuery } from '@tanstack/react-query';
import { VerticalChart } from '@surf/charts';
import Loader from '@components/Loader';
import ErrorImage from '@components/ErrorImage';
const fetchSalesData = async () => {
const response = await fetch('/api/sales');
if (!response.ok) {
throw new Error('Failed to fetch sales data');
}
return response.json();
};
export function DynamicDataChart() {
const { data, status } = useQuery(['salesData'], fetchSalesData);
const statuses = {
pending: <Loader />,
error: <ErrorImage />
};
const labels = {
pending: 'Wait...',
error: 'An error occurred'
};
return (
<VerticalChart
label='Monthly Sales'
data={data}
tooltipPostfix='K'
noDataContent={statuses[status]}
noLabelContent={labels[status]}
/>
);
}In this example, the following occurs:
- There's a request for data and we get a
pendingstatus, so chart displays theLoadercomponent. - If an error occurs than the chart will display some custom
ErrorImagecomponent. - If
Datais successfully arrived than chart automatically displays it.
That's it. It's easy, isn't it?
This way you can replace TanstackQuery with your favorite query manager. You can also create your own status handling system. Don't be afraid to experiment, good luck!
Last updated on 9/8/2024