#Fetching infinite query data without any UI action to invoke fetchNextPage
6 messages · Page 1 of 1 (latest)
use an infinite query and call fetchNextPage() in an effect as long as you like ?
@crystal ember ok. Thanks for the quick response. so I tried to create a custom hook to solve this
const [isLoading, setIsLoading] = useState(true);
const {
data
status
fetchNextPage,
fetchStatus,
hasNextPage
} = useInfiniteQuery({
queryKey: ['test'],
queryFn: getData,
getNextPageParam: (lastPage, pages) => {
return lastPage?.next?.split('offset=')[1].split('&')[0];
},
initialPageParam: 0
});
useEffect(() => {
fetchNextPage();
if (hasNextPage) {
setIsLoading(false);
}
}, [fetchNextPage, useTraps, hasNextPage]);
const allItems = useTraps?.pages.flatMap((page) => page?.results);
return { allItems, status, isLoading };
};
@crystal ember Do you think it's a correct approach ? Moreover, since I'm fetching the data in a loop, don't have the correct loading status till the complete data is loaded. so, do you think having local useState to maintain the loading status makes sense here ? Thank you so much. I'm new to react native and React Query. Apologies for silly questions.
if you want to display a loader until all pages are fetched, I'd rather make one useQuery where you fetch in a loop inside the queryFn. The advantage of an infinite query is that you can show the first page while the others are still fetching. But it seems like you don't need that...