Customizing Queries with Query Keys and Options
Showcase how to use query keys to uniquely identify queries and how to customize queries further with options such as stale time and cache time.
import { useQuery } from 'react-query';
const fetchUserData = async (userId) => {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Network response was not ok.');
return response.json();
};
Defines an asynchronous function fetchUserData to fetch user data from an API. This function will be used as the query function for the useQuery hook.
const userId = '123';
const userInfoQueryKey = ['userData', userId];
Sets up a unique query key for identifying the user data query. This array includes a base key 'userData' and the dynamic userId to ensure the query key is unique per user.
const { data, isLoading, error } = useQuery(userInfoQueryKey, () => fetchUserData(userId), {
staleTime: 1000 * 60 * 60 * 24, // 24 hours in milliseconds
cacheTime: 1000 * 60 * 5, // 5 minutes in milliseconds
refetchOnWindowFocus: false
});
Uses the useQuery hook to fetch the user data. The query is uniquely identified by the userInfoQueryKey. Options are configured to set the data as stale after 24 hours, cache data for 5 minutes, and disable refetching on window focus.