Skip to content

readField() in type policy merge function returns undefined only on first query #9315

@miracle2k

Description

@miracle2k

I was using @apollo/client@3.3.19 with a custom type policy to do pagination merging based on what is described here:

https://www.apollographql.com/docs/react/caching/cache-field-behavior/#merging-non-normalized-objects

My merge function looks as follows. It is intended to merge a connection-type entity with a nodes subkey, so something like:

query { 
  platform {
      events {
           nodes {
               id
           }
      }
  }
}

Here it is:

merge(existing: any, incoming: any, { args, readField }: any) {
      const { nodes: incomingNodes, ...rest } = incoming || {};

      let mergedNodes: Map<string, any>;
      if (existing?.nodes) {
        mergedNodes = new Map(existing.nodes);
      } else {
        mergedNodes = new Map();
      }

      incomingNodes?.forEach((item: any) => {
        mergedNodes.set(readField("id", item), item);
      });

      return {...rest, nodes: mergedNodes};
    },

This worked fine. After upgrading to @3.5.7 I see the following behaviour:

  1. The first time useQuery() gets a result, readField("id", item) returns undefined. Because of this, only a single node is actually stored in the cache.
  2. On subsequent requests (say to load the second page), readField works correctly.

I don't have a repo, but wonder if it is related to https://github.com/apollographql/apollo-client/pull/8508/files

Note: nodes is an interface type called Event, the nodes returned from the server are a concrete type implementing the interface (SaleEvent). I am defining possibleTypes in the cache (it implements both interfaces):

{
   Event: ['SaleEvent'],
   MarketplaceEvent: ['SaleEvent'],
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions