apollo-client icon indicating copy to clipboard operation
apollo-client copied to clipboard

Uncaught Invariant Violation: Missing field 'name' while computing key fields

Open hamzahamidi opened this issue 1 year ago • 1 comments

Hello I'm getting the following error when I add the field name as a key for caching in the typePolicies

  Offer: {
    keyFields: ['__typename', 'id', 'name'],
  },

This sometimes doesn't work as sometimes in the application we don't fetch the name field from the resolver Offer. So I get the following error:

Uncaught Invariant Violation: Missing field 'name' while computing key fields

Uncaught Invariant Violation: Missing field 'name' while computing key fields

Is there any way I could make the usage of the key optional, so we can bypass this this error? or maybe add a scope for the specific queries that don't use the name field?

hamzahamidi avatar Aug 18 '22 05:08 hamzahamidi

You can provide your own keyFields function for more control:

new InMemoryCache({
  typePolicies: {
    Offer: {
      keyFields(object, context) {
        // In addition to returning a string ID immediately, a custom keyFields
        // function can return a dynamic array of field names, letting the usual
        // keyFields machinery handle extraction and stringification
        if (object.name) return ["id", "name"];
        return ["id"];
      }
    }
  }
})

benjamn avatar Sep 15 '22 18:09 benjamn