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?
The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).
A GraphQL fragment is a piece of logic that can be shared between multiple queries and mutations. Every fragment includes a subset of the fields that belong to its associated type. In the above example, the Person type must declare firstName and lastName fields for the NameParts fragment to be valid.
GraphQL in Action MEAP V05 Inline fragments are, in a way, similar to anonymous functions that you can use without a name. They are just fragments without names and you can spread them inline where you define them.
Generally, when caching data, the intuition is to put information that's fetched remotely into a local store from where it can be retrieved later on. With GraphQL, the naive approach would be to simply put the results of GraphQL queries into the store and simply return them whenever the same query is sent.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With