Blog>
Snippets

Implementing a Custom Hook for Data Fetching

Show how to create a custom hook with TanStack Store that encapsulates data fetching logic, including loading, error, and data state.
import { useState, useEffect } from 'react';
import { useStore } from '@tanstack/react-store';

export function useFetchData(url) {
  const [state, setState] = useStore((state) => state);
  
  useEffect(() => {
    const fetchData = async () => {
      setState({ loading: true, error: null });
      try {
        const response = await fetch(url);
        const data = await response.json();
        setState({ data, loading: false });
      } catch (error) {
        setState({ error, loading: false });
      }
    };
    
    fetchData();
  }, [url, setState]);
  
  return state;
}
This code defines a custom hook `useFetchData` that encapsulates the logic for fetching data from a provided URL using the Fetch API. It leverages TanStack Store for state management within the hook, handling the loading, data, and error states.
import { createStore } from '@tanstack/store-core';

const store = createStore({
  initialState: {
    loading: false,
    data: null,
    error: null
  }
});
Before using the `useFetchData` hook in a component, initialize the TanStack Store with an `initialState` containing `loading`, `data`, and `error` keys to hold the states necessary for handling the asynchronous data fetching logic.