Blog>
Snippets

Managing Query Cache for Dynamic Data

Show how to use TanStack Ranger's cache management features to store, retrieve, and update cached query results for dynamic data sources.
import { useQuery, QueryClient, QueryCache } from '@tanstack/react-query';

// Initialize a new Query Client with a custom Query Cache
const queryClient = new QueryClient({
  queryCache: new QueryCache({
    // Define a custom stale time for the cache
    defaultOptions: { queries: { staleTime: 5 * 60 * 1000 } }
  })
});
This piece initializes a new Query Client with a custom Query Cache, setting a default stale time of 5 minutes for the cached queries.
const fetchData = async (key) => {
  // Simulate fetching dynamic data
  const response = await fetch(`https://api.example.com/data/${key}`);
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
};
Defines an asynchronous function to fetch dynamic data from a hypothetical API, using a dynamic key to fetch different pieces of data.
const useDynamicData = (key) => useQuery(['dynamicData', key], () => fetchData(key), {
  // Option to enable or disable cache based on the key
  cacheTime: key ? 10 * 60 * 1000 : 0
});
Defines a custom hook to fetch and cache dynamic data, with the cache time set based on whether a key is provided, enabling longer caching for specific keys.
// Using the custom useDynamicData hook to fetch and display data
function DynamicComponent({ dataKey }) {
  const { data, error, isLoading } = useDynamicData(dataKey);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return <div>Dynamic Data: {JSON.stringify(data)}</div>;
}
Demonstrates how to use the custom hook within a component to fetch, display the dynamic data, and handle loading and error states.
// Manually updating cache for a specific query
queryClient.setQueryData(['dynamicData', 'specificKey'], updatedData);
Shows how to manually update the cache for a specific query identified by a unique key, allowing for dynamic updates to cached data without refetching.