RN Apollo Client 3.0 - handle refetch with merge function

Viewed 1930

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.

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],
                };
              },
            },
          },
        },
      },
    });
Related