12

I can't find or I am looking in the wrong place for any documentation on how fragments are matched. When I use the vanilla Apollo client if I turn off the option of addTypename when I use fragments I get a warning heuristic fragment matching going on! and if I add it this goes away but my response contains many __typename fields which I don't need. Why do they help?

Barry
  • 1,800
  • 2
  • 25
  • 46
  • 2
    Maybe that won't fully satisfy your question, but `__typename` seems to be the only trace by which Apollo is able to match fragments in it's cache. I think that to tackle this you don't need to pass `addType: true` - keep it false and instead try adding `__typename` to your fragment. – jalooc Aug 30 '17 at 13:35

1 Answers1

9

The reason for this is that ApolloClient, like Relay, uses a global store to cache your data on the client.

In order to do this for you, global ids are required. For some reason, global ids are not something people think about, and in fact, it is something people complain about when switching to Relay all the time.

ApolloClient has a clever solution for this! (Apollo team correct me if I am wrong) They allow you to define how your records get keyed in the store! By default, it uses the typename and id to create a the kind of global IDs that Relay suggests you create. This is why they need the typename.

Since you are turning off the typename in the query, Apollo will do some smart stuff to try and figure out the type (and thus the key in the store). This smart stuff can lead to problems for you down the road.

If you want to create your own global ids instead of using all this smart stuff, you can specify it like so:

const cache = new InMemoryCache({
  dataIdFromObject: object => object.key || null
});

https://www.apollographql.com/docs/react/advanced/caching.html#normalization

brysgo
  • 838
  • 1
  • 8
  • 20