Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RN Apollo Client 3.0 - handle refetch with merge function

I am recently migrating to apollo client 3.0 from 2.0.

I have a query that requires fetch more and pagination.

By doing,

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        getData: {
          // Handles incoming data
          keyArgs: [],
          merge(existing ={/*some default object fields*/}, incoming) {
            return {
              ...existing,
              pageInfo: incoming.pageInfo,
              edges: [...existing.edges, ...incoming.edges],
            };
          },
        },
      },
    },
  },
});

I was able to handle both initial query/fetch and pagination. However, I am having trouble with how to handle refetch. With this merge function, refetched data get just concatenated with existing cache data. I am not able to find how to correctly handle this in merge function.

If anyone know how to handle this, please let me know.

like image 714
Bubu Avatar asked May 24 '26 16:05

Bubu


1 Answers

I was able to work around by observing args.

const cache = new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            getData: {
              // Handles incoming data
              keyArgs: [],
              merge(existing ={/*some default object fields*/}, incoming, {args}) {
                if(args && !args.after){
                    // Initial fetch or refetch
                    return incoming;
                }
                
                // Pagination
                return {
                  ...existing,
                  pageInfo: incoming.pageInfo,
                  edges: [...existing.edges, ...incoming.edges],
                };
              },
            },
          },
        },
      },
    });
like image 92
Bubu Avatar answered May 27 '26 18:05

Bubu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!