Complex Query Key Structure for Nested Resources
Provide an example of how to structure complex query keys for nested resources, enabling precise targeting for invalidation and refetching without affecting unrelated data.
const fetchProductDetails = ({ queryKey }) => {
const [, { productId, locale }] = queryKey;
return fetch(`/api/products/${productId}?locale=${locale}`).then(res => res.json());
};
Defines a function to fetch product details. The function extracts the `productId` and `locale` from the query key structure to make a fetch request.
const productQueryKey = productId => locale => ['product', { productId, locale }];
Provides a factory function for generating structured query keys. It returns a function that takes a `locale` and returns a structured array suitable as a query key. This structure allows for precise targeting.
const { data: productDetails } = useQuery(productQueryKey(productId)(locale), fetchProductDetails, {
staleTime: 1000 * 60 * 10 // 10 minutes
});
Example usage of useQuery with a complex key structure. It fetches product details based on `productId` and `locale`. The example illustrates how to apply the query key and fetch function.
queryClient.invalidateQueries(['product', { productId }]);
Invalidates all queries related to a specific product regardless of the locale. This demonstrates how to target a specific set of data for invalidation.