'Apollo Client fetchMore get previous page for cursor based pagination

I know for a fact that to get the next page via cursor based pagination you need to example if query is product:

 products(first:12, after: endCursor,)

Get the first n edges after your end cursor.

And to get the previous page is you need to:

 products(last:12, before: startCursor,)

Get the last n data before your start cursor.

The problem I have with apollo client is when I useQuery and fetchMore or refetch it retains the first variable from that query.

 const { loading, error, data, fetchMore, networkStatus } = useQuery(PRODUCTS,{
        variables: { first: 12, after: null },
        notifyOnNetworkStatusChange: true,
    });

and when I get the previous page:

await fetchMore({
        variables: {
            before: pageInfo.startCursor,
            last:12
        }
    });

Then in I get a query of:

variables: {
        before: pageInfo.startCursor,
        last:12,
        first:12
    }

which returns an invalid page.

My question is how can I remove the 'first' variable if I do the previous page query.



Solution 1:[1]

This was how I worked around this problem due to fetchMore use variables from original query. To remove the variable that you don't want them to be included in query called by fetchMore, simply pass undefined or null to overwirte its original value.

For your specific case, you can do like below:

fetchMore({
 variables: {
  before: pageInfo.startCursor,
  last: 12,
  first: undefined,
 }
})

So that the payload variable of the query is below if the value you pass is undefined:

{
 before: <cursorValue>
 last: 12
}

or below if the value you pass is null:

{
 before: <cursorValue>
 last: 12
 first: null
}

Hope that helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1