Search code examples
react-nativeinfinite-loopinfinite-scrollreact-query

useInfiniteQuery doesnt go to the next page


I have this code in react native, where i am trying to implement react-query:

  const { data, isLoading, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, refetch } =
    useInfiniteQuery<BovinePaginator, Error>(
      [API_ENDPOINTS.BOVINE_IDENTIFICATION, options],
      ({ queryKey }) => client.bovine.all(queryKey[1] as object),
      {
        getNextPageParam: ({ meta }) => meta.last_page > meta.current_page && { page: meta.current_page + 1 },
        enabled: false,
      },
    );

My problem is in the getNextPageParam where meta has this response:

{"current_page": 1, "from": 1, "last_page": 2051, "path":"url_here", "per_page": "10", "to": 10, "total": 20507}

The problem is that current_page doesn't update its value and stays 1. And the refetch keeps returning in infinite the same first values. Any idea how to fix it ??

Thank you!!


Solution

  • i found this as a permanant solution:

    I apologize for the oversight. You are correct; the allPages parameter in the getNextPageParam function is not being used in the code. Let's revise the code to use allPages correctly to determine whether there are more pages to fetch:

    const { data, isLoading, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, refetch } =
      useInfiniteQuery<BovinePaginator, Error>(
        [API_ENDPOINTS.BOVINE_IDENTIFICATION, options],
        ({ pageParam = 1 }) => {
          // Use pageParam instead of hardcoding the page number
          return client.bovine.all({ ...options, page: pageParam });
        },
        {
          // Use getNextPageParam to determine when to fetch the next page
          getNextPageParam: (_, allPages) => {
            // Check if there are more pages to fetch
            const lastPage = allPages[allPages.length - 1];
            if (lastPage.meta.current_page < lastPage.meta.last_page) {
              // Increment the current page by 1 for the next fetch
              return lastPage.meta.current_page + 1;
            } else {
              // No more pages to fetch
              return undefined;
            }
          },
          enabled: false,
        },
      );
    

    In this revised code:

    1. We use allPages to access the last page of data fetched. allPages is an array containing all previously fetched pages, and we use the last page to determine if there are more pages to fetch.

    2. We check if there are more pages to fetch by comparing the current_page of the last page with the last_page. If there are more pages, we increment the current page by 1 for the next fetch. If not, we return undefined to indicate that there are no more pages to fetch.

    This should ensure that the getNextPageParam function works correctly to fetch additional pages when needed.