#Fetching infinite query data without any UI action to invoke fetchNextPage

6 messages · Page 1 of 1 (latest)

thick drift
#

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?

crystal ember
#

use an infinite query and call fetchNextPage() in an effect as long as you like ?

thick drift
#

@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.

crystal ember
#

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...