T
TanStack•2y ago
conscious-sapphire

Fetching infinite query data without any UI action to invoke fetchNextPage

Hi, I have a use case where I need to call a paginated API but I need to show all the data at once on UI instead of asking the user to load the next page. Since I can't invoke the api to return all data at once, is there a way to achieve this by fetching all pages in the background without any use interaction?
4 Replies
rival-black
rival-black•2y ago
use an infinite query and call fetchNextPage() in an effect as long as you like ?
conscious-sapphire
conscious-sapphireOP•2y ago
@TkDodo 🔮 ok. Thanks for the quick response. so I tried to create a custom hook to solve this ```export const useCustomHook = () => { 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 }; }; @TkDodo 🔮 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.
rival-black
rival-black•2y ago
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...
conscious-sapphire
conscious-sapphireOP•2y ago
ok, Got it. Thanks!

Did you find this page helpful?