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 3 years 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

Hey @hamzahamidi, I'd recommend trying the recommendation by @benjamn in https://github.com/apollographql/apollo-client/issues/10015#issuecomment-1248458358.

Since there has been no activity in this issue for a bit, I'm going to go ahead and close this issue. If you need additional help or the recommendation doesn't help, feel free to open the issue back up. Thanks!

jerelmiller avatar Jan 04 '23 22:01 jerelmiller