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

How to I pass a filters variable to useInfiniteQuery with pageParam?

1个答案

1

In React Query, when using InfiniteQuery to implement infinite scrolling, you may encounter scenarios where you need to dynamically adjust request data based on filter conditions (such as user input or selected tags). To integrate filter variables with pageParam, follow these steps:

1. Define Initial Filter Conditions and Query Function

First, define the initial filter conditions and create a query function to fetch data based on these conditions and the page number. For example:

javascript
import { useInfiniteQuery } from 'react-query'; function usePosts(filter) { return useInfiniteQuery( ['posts', filter], // Include filter conditions in the query key using an array to trigger data re-fetching when conditions change ({ pageParam = 1 }) => fetchPosts(pageParam, filter), { getNextPageParam: (lastPage, pages) => lastPage.nextPage, } ); } async function fetchPosts(page, filter) { const response = await fetch(`/api/posts?page=${page}&filter=${filter}`); return response.json(); }

2. Implement Filters in the Component

Next, in your component, dynamically set filter conditions based on user interactions and pass these conditions to the usePosts hook.

javascript
function PostsComponent() { const [filter, setFilter] = useState(''); const handleFilterChange = (event) => { setFilter(event.target.value); }; const { data, error, fetchNextPage, hasNextPage, isFetchingNextPage, status, } = usePosts(filter); return ( <> <input type="text" value={filter} onChange={handleFilterChange} /> {data?.pages.map((page) => page.results.map((post) => <p key={post.id}>{post.title}</p>) )} <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}> Load More </button> </> ); }

3. Optimize Performance with useEffect (Optional)

If data updates are too frequent or cause performance issues, delay or limit request frequency using useEffect.

javascript
useEffect(() => { const handle = setTimeout(() => { refetch(); // Trigger a re-fetch }, 500); // Delay for 500 milliseconds return () => clearTimeout(handle); }, [filter, refetch]);

Summary

This approach enables you to combine InfiniteQuery with dynamic filter conditions for complex data loading requirements. When users change filter conditions, react-query automatically re-initiates requests to fetch new data while maintaining page state and seamless infinite scrolling.

2024年8月5日 11:32 回复

你的答案