Tracking page number in cursor based pagination with graphql cache in use

Viewed 716

I have a GQL cursor based pagination and have implemented the frontend in react using the apollo client library. This is my current server response, and things work well when requesting the next or the previous page.

{
  "data": {
    "users": {
      "pageInfo": {
        "hasNextPage": true,
        "hasPreviousPage": false,
        "startCursor": "1",
        "endCursor": "6"
      },
      "edges": [
        {
          "node": {
            "id": "1"
          }
        },
        {
          "node": {
            "id": "6"
          }
        }
      ]
    }
  }
}

The issue which I have is;

I have a page count dropdown, 20, 50 and 100, which determines the number of record to be show on a page. So, if i start with 50 records per page, and let's say record number 74 is on page 2, when i switch to 20 records per page, the apollo client does not request the server, instead loads the data from the cache. This is good as caching helps avoid additional request, but now I do not know which page record 74 belongs to.

Solution I am after;

I am after a solution/library that can handle pagination in react which also takes into account the fact that the server wont be contacted always and therefore should keep track of the page.

1 Answers

So, after some deep dive into apollo and graphql cursors, there isn't a way for react to "guess" the start cursor for a particular page, and therefore is not practically possible for pagination to place nice when the cache is in play.

For this reason, I had to disable cache for this specific query using the following

const { loading, error, data } = useQuery(GET_GREETING, {
    variables: { ... },
    fetchPolicy: "network-only"
});

This will make sure the query is always fetched from the network and is not cached.

Related