Managing Async Data Fetching and Caching
Provide an example of managing asynchronous data fetching, updating the state, and implementing caching strategies with TanStack Store.
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
// Initialize a new Query Client
const queryClient = new QueryClient();
This code snippet is used to import necessary functions and classes from the TanStack Query library and initializes a new Query Client. The Query Client is responsible for managing queries and their caching, synchronization, and updates.
function fetchData() {
return fetch('https://api.example.com/data').then(res => res.json());
}
Defines a simple fetchData function that fetches data from an example API and returns the JSON response. This function will be used with TanStack Query to fetch and cache the data asynchronously.
function App() {
// Using the useQuery hook to fetch and cache data
const { data, isError, isLoading } = useQuery(['uniqueKeyForData'], fetchData);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error occurred</div>;
return (
<div>
{data.map(item => (
<div key={item.id}>{item.title}</div>
))}
</div>
);
}
Creates a functional component that uses the useQuery hook from TanStack Query to fetch and cache the data returned by fetchData. It provides a unique key for cache identification. Also handles loading and error states to render appropriate UI elements.
function Root() {
return (
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
}
Wraps the App component with the QueryClientProvider and passes the previously created queryClient to it. This setup is necessary to provide the App component (and any nested components) access to the QueryClient functionalities.