Blog>
Snippets

Using Custom Hooks for Data Fetching and State Management in Charts

Show how to create and use a custom hook in React for fetching data from an API and managing the state of the chart data for a TanStack React Chart component.
import { useState, useEffect } from 'react';

function useChartData(apiUrl) {
  const [chartData, setChartData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        setChartData(data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [apiUrl]);

  return { chartData, loading, error };
}
Defines a custom hook useChartData for fetching chart data from an API. This hook uses useState to manage chart data, loading state, and any errors. It uses useEffect to fetch data asynchronously when the component mounts or the apiUrl changes.
import React from 'react';
import { Chart as ChartJS } from 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
import useChartData from './useChartData';

function ChartComponent({ apiUrl }) {
  const { chartData, loading, error } = useChartData(apiUrl);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error loading data</p>;

  // Assuming chartData is formatted correctly for ChartJS
  return <Chart type='line' data={chartData} />;
}
This component, ChartComponent, uses the custom hook useChartData to fetch the chart data from an API. It handles loading and error states and renders a Chart.js line chart with the fetched data, assuming the data is in the correct format for Chart.js.