Blog>
Snippets

Custom Hook for Asynchronous Data Fetching in Charts

Create a custom React hook that fetches data asynchronously and updates the chart, demonstrating how to integrate it with TanStack React Charts.
import { useState, useEffect } from 'react';
import axios from 'axios';
Imports the necessary hooks from React and axios for making HTTP requests.
const useFetchChartData = (url) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    axios.get(url)
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
};
Defines a custom hook useFetchChartData to asynchronously fetch data for the chart. It returns the fetched data, loading state, and any error encountered.
import { useChart } from '@tanstack/react-charts';

function MyChartComponent() {
  const { data, loading, error } = useFetchChartData('https://api.example.com/data');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  // Transform data for the chart if necessary

  const chartData = {
    labels: data.map(item => item.label),
    datasets: [{
      label: 'Dataset 1',
      data: data.map(item => item.value),
    }],
  };

  const chart = useChart({
    type: 'bar', // or any other type
    data: chartData,
  });

  return <div>{chart}</div>;
}
This component uses the custom hook useFetchChartData to fetch data and then uses it to render a chart with TanStack React Charts. It handles loading and error states.