乐闻世界logo
搜索文章和话题

How to call API only once with React Query?

7 个月前提问
5 个月前修改
浏览次数93

1个答案

1

Certainly, to ensure an API call is made only once with React Query, you can use the useQuery hook along with the proper configuration to fetch the data. React Query automatically deduplicates multiple requests for the same query key to a single request. Here’s how you can achieve this:

javascript
import { useQuery } from 'react-query'; // Define your API fetch function const fetchMyApi = async () => { // replace with your actual API call const response = await fetch('https://my-api/service'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; function MyComponent() { // Use the useQuery hook to fetch data const { data, error, isLoading, isFetching } = useQuery( 'myUniqueQueryKey', // This key is used internally by React Query to manage the queries fetchMyApi, // Your fetch function { // Optional configurations // If you want to cache the data and not refetch it, you can set the stale time to infinity staleTime: Infinity, // To avoid refetching on window focus, you can set refetchOnWindowFocus to false refetchOnWindowFocus: false, // To disable automatic retries on failure, you can set retry to false retry: false, // You can also specify that the query should not refetch on mount if the data is already in the cache refetchOnMount: false, } ); if (isLoading) { return <span>Loading...</span>; } if (error) { return <span>An error occurred: {error.message}</span>; } // Render your component with the fetched data return ( <div> {/* Render your API data here */} <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }

In this example, the useQuery hook is used with a unique query key ('myUniqueQueryKey') and a fetch function (fetchMyApi). The configuration options are set to ensure the API call is not made again under certain circumstances, like cached data (staleTime: Infinity), window refocus (refetchOnWindowFocus: false), component remount (refetchOnMount: false), and on failure retries (retry: false).

The query will run once and the result will be cached. Any other component that uses the same query key will use the cached data instead of making a new API call, as long as the cached data is not invalidated or considered stale according to the options you've set.

Remember that React Query's defaults are designed with the assumption that your data may change and therefore should be periodically updated, which is why the defaults are relatively aggressive about refetching. Adjusting these options gives you control over the behavior to fit your specific needs.

2024年6月29日 12:07 回复

你的答案