Blog>
Snippets

Integrating TanStack Query with TanStack Config

Provide an example of how to configure TanStack Query for data fetching using settings managed by TanStack Config, emphasizing ease of integration and configuration sharing.
import { createConfig } from 'tanstack-config';

// Define your configurations for different environments
const appConfig = createConfig({
  key: 'app',
  defaultConfig: {
    apiUrl: 'http://localhost:3000/api',
  },
  development: {
    apiUrl: 'http://dev.myapi.com/api',
  },
  production: {
    apiUrl: 'https://prod.myapi.com/api',
  },
});
This code creates a central configuration using TanStack Config, defining API URL settings for different environments (development and production).
import { useQuery } from 'tanstack-query';
import { useConfig } from 'tanstack-config';

function fetchTodo(id) {
  // Access the centralized configuration
  const config = useConfig();
  return fetch(`${config.apiUrl}/todos/${id}`)
    .then(response => response.json());
}

function Todo({ todoId }) {
  // Use TanStack Query to fetch data using the API URL from TanStack Config
  const { data: todo, isLoading } = useQuery(['todos', todoId], () => fetchTodo(todoId));

  if (isLoading) return <div>Loading...</div>;
  return <div>{todo.title}</div>;
}
This code demonstrates how to fetch data using TanStack Query, utilizing the API URL defined in TanStack Config, showing the integration of both libraries for effective configuration sharing and data fetching.