Apollo InMemoryCache syntax

Viewed 280

I’ve inherited a project that’s setting an inmemorycache with the following key field syntax. None of the examples showcase this particular signature (that I can find at least). All the fields I see in the examples use multiple fields and are placed in the key field attribute. Is this looking for any nested “myField” attributes? How is this expected in the graphql data? (Apollo client 3.2)

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
         /// query info
      },
    },
    UserData: {
      fields: {
        fieldA: {
          merge(existing = [], incoming = []) {
            return incoming;
          },
        },
        fieldB: {
          merge(existing = [], incoming = []) {
            return incoming;
          },
        },
      },
      keyFields: [["myField"]], // <-- What is this looking for?
    },    
  },
});

This leads to an invariant violation error:

Uncaught Invariant Violation: Missing field 'myField' while extracting keyFields from {"id":"462a349...... (does not contain myField)
1 Answers

Your code seems fine when it comes to fields map. On the other hand, keyFields in a slightly different question. You could totally skip setting it.

The purpose of keyFields is to uniquely identify your record, so the cache would know how to update. Just like in the relational databases you have a primary key that consists of one or more columns that consider your record unique.

I believe this is well documented in Apollo's documentation, see this: https://www.apollographql.com/docs/react/caching/cache-configuration/#customizing-cache-ids

Related