0

I have a problem with useInfiniteQuery. This is my code:

const { data, hasNextPage, fetchNextPage, isFetching, isLoading } =
 useInfiniteQuery(
 "explorePosts",
      ({ pageParam = 1 }) => fetchExplorePosts(pageParam),
      {
 getNextPageParam: (lastPage, allPages) => {
 const maxPages = lastPage.info.pages;
 const nextPage = allPages.length + 1;
 return nextPage <= maxPages ? nextPage : undefined;
        },
 refetchOnWindowFocus: false,
      }
    );

Now, the code works fine and all, but where the problem occurs is when the data being paginated changes in the middle of the pagination process.

For example:

If I fetch 10 posts with 2 posts per page (5 pages total) and I fetch the first 4 posts via 2 instances of the paginated query, then I delete the last 2 posts fetched, so my overall number of posts now decreases to 8 (and my number of pages decreases to 4). Now, since my maxPages var takes the number of posts displayed in the last API call (last object in the pages array), and the nextPage var does so as well, it makes the query fetch the data on page 3, but since two posts were deleted from page two, this moves posts number 5 and 6 to page two, and causes posts 7 and 8 to be fetched instead (because posts 7 and 8 now move to page 3, since two posts were deleted, so basically posts 5 and 6 get skipped in the process). Is there any easy way to fix this, because it seems like a problem that the react query devs might have already thought about, or am I going to have to bust my balls for a few days in order to get it working?

P.S. The problem I am describing here is a very oversimplified version of the problem I need to fix, but some brainstorming and directions could help me a lot (maybe you know some R.Q. features designated for problems like these that I missed...)

2
  • do you invalidate the query after the deletions? It should refetch to have your data kept up-to-date so that these things don't happen ... Commented Nov 26, 2022 at 8:10
  • Yea I fixed the behaviour by using refetch Commented Nov 26, 2022 at 15:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.