Blog>
Snippets

Integrating TanStack Config with React Query for Enhanced Data Fetching

Provide an example of how to use TanStack Config to manage API endpoints and integrate with React Query for efficient data fetching and state management.
import { createQuery } from '@tanstack/react-query';
import { config } from './config'; // Assume this exports an object with API endpoints

// Create a custom hook for fetching users
export const useFetchUsers = () => {
  // Define the query key
  const queryKey = ['users'];
  // Use the TanStack React Query's useQuery hook with queryKey and query function
  return createQuery(queryKey, async () => {
    const response = await fetch(`${config.apiBaseUrl}/users`);
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json();
  });
}
This code demonstrates how to integrate TanStack Config with React Query by defining a custom hook for data fetching. It utilizes a `config` object that holds the API endpoints. The `useFetchUsers` hook uses React Query's `createQuery` to fetch user data from a specified endpoint and manage the data's state.