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

How to pass more parameters in useInfiniteQuery?

1个答案

1

The methods for passing additional parameters in the useInfiniteQuery hook of React Query can be implemented in various ways, depending on how you choose to construct and utilize these parameters. Specifically, you can directly use these parameters within the query function, or include them in the queryKey.

Option One: Using Parameters Within the Query Function

When defining the query function, you can directly reference external variables or parameters within it. This approach allows your query function to dynamically adjust the behavior or content of the request based on these parameters.

javascript
import { useInfiniteQuery } from 'react-query'; function fetchProjects(page = 0, pageSize = 10, filter = "") { return fetch(`api/projects?page=${page}&pageSize=${pageSize}&filter=${filter}`) .then(res => res.json()); } function ProjectsComponent({ pageSize, filter }) { const { data, error, fetchNextPage, hasNextPage, isFetchingNextPage, status } = useInfiniteQuery( ['projects', { pageSize, filter }], ({ pageParam = 0 }) => fetchProjects(pageParam, pageSize, filter), { getNextPageParam: (lastPage, allPages) => lastPage.nextPage, } ); // UI part }

Option Two: Passing Parameters via queryKey

In useInfiniteQuery, the queryKey is not merely a simple string or array; it can contain objects, enabling you to embed additional parameter information within it. The React Query library determines when to re-fetch data based on the content of queryKey. If parameters in queryKey change, React Query will automatically re-run the query function.

javascript
import { useInfiniteQuery } from 'react-query'; function fetchProjects({ queryKey, pageParam = 0 }) { const [_key, { pageSize, filter }] = queryKey; return fetch(`api/projects?page=${pageParam}&pageSize=${pageSize}&filter=${filter}`) .then(res => res.json()); } function ProjectsComponent({ pageSize, filter }) { const { data, error, fetchNextPage, hasNextPage, isFetchingNextPage, status } = useInfiniteQuery( ['projects', { pageSize, filter }], fetchProjects, { getNextPageParam: (lastPage, allPages) => lastPage.nextPage, } ); // UI part }

Comprehensive Comparison and Recommendations

Both methods effectively pass additional parameters to useInfiniteQuery. The choice depends on your specific requirements:

  • If your parameters change infrequently or are closely tied to the UI state, it is recommended to use Option One, directly utilizing these parameters within the query function.
  • If your parameters frequently change and require fetching new data from the server each time, it is recommended to use Option Two, placing parameters in the queryKey, so that React Query automatically handles caching and data re-fetching.
2024年6月29日 12:07 回复

你的答案