query icon indicating copy to clipboard operation
query copied to clipboard

Refetching bidirectional infinite query skipping first page

Open brian-bourdon opened this issue 11 months ago • 0 comments

Describe the bug

I file this issue after some discussions on the tanstack discord about this problem. I will try my best to explain it but the easiest way to understand is with an example i think:

Here is a simplified example of a bidirectional infinite query using cursor (id is the cursor here): The 1st page is fetched then fetchPreviousPage() is used to fetch the 2nd page.

2nd fetched page:

{
 items: [
    { "name": "Project 0", "id": 114 },
    { "name": "Project 1", "id": 113 },
    { "name": "Project 2", "id": 82 },
    { "name": "Project 3", "id": 80 },
    { "name": "Project 4", "id": 67 }
  ],
  prevCursor: null,
  nextCursor: 4,
}

1st fetched page:

{
  items: [
    { name: "Project 0", id: 4 },
    { name: "Project 1", id: 8 },
    { name: "Project 2, id: 12 },
    { name: "Project 3", id: 41 },
    { name: "Project 4", id: 42 },
  ],
  prevCursor: 67,
  nextCursor: null,
}

When refetch happens, it will call the endpoint with direction forward and cursor 67. The problem here is that the first page is skipped entirely (because of direction forward).

Atm for refetch to work i should return as prevCursor the first item's id of the previous page so in this case 114. In this case on first refetch the endpoint would be called with direction forward and cursor 114 and will correctly fetch the first page and the others. But the problem with this method is that since the previous cursors are not predictable i would have to fetch the whole previous page just to return the first items id as cursor in each request. So it is not really optimal.

A solution suggested by @TkDodo on discord was on tanstack/query side "to store the original direction next to pages and pageParams, then pass that as direction to the first refetch". So the first refetch will have direction backward correctly fetching the first page and then the others.

Your minimal, reproducible example

https://stackblitz.com/edit/tanstack-query-bs7ooo?file=src%2Fpages%2Findex.js

Steps to reproduce

  1. Go to https://stackblitz.com/edit/tanstack-query-bs7ooo?file=src%2Fpages%2Findex.js
  2. Load older one time
  3. Refetch the ["projects"] query using tanstack/query devtools
  4. We can see that the first page is skipped

Expected behavior

The query is correctly refetch beginning from the first page.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Any

Tanstack Query adapter

react-query

TanStack Query version

5.28.10 (latest)

TypeScript version

5.4.3 (but issue not related to typescript)

Additional context

No response

brian-bourdon avatar Mar 30 '24 17:03 brian-bourdon