Integrating TanStack Config with TanStack Query
Display a practical example of using TanStack Config to manage API endpoint URLs and other settings for TanStack Query to fetch data.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// Initialize a Query Client with TanStack Config
const queryClient = new QueryClient({
defaultOptions: {
queries: {
// Set the endpoint URL for fetching data
queryFn: async ({ queryKey }) => {
const response = await fetch(`https://myapi.com/${queryKey[0]}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
},
// Other TanStack Query configurations...
},
},
});
// Wrap your components with QueryClientProvider
texport function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your app's components go here */}
</QueryClientProvider>
);
}
This example demonstrates how to integrate TanStack Config with TanStack Query. We initialize a QueryClient from TanStack Query, where we set up the default options to define the API endpoint URL for fetching data. We then wrap our application components with QueryClientProvider, passing in the configured queryClient. This setup will manage API endpoint URLs and other settings for data fetching.