3
votes

I am getting the following error when attempting to fetch a query fragment:

"You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: https://www.apollographql.com/docs/react/recipes/fragment-matching.html"

This is the call that triggers the error.

const sourceData = cache.readFragment({
        id: `${typename}:${idToAdd}`,
        fragment: gql`
          ${sourceFragment}
        `,
      });

where sourceFragment is

fragment series on PriceSeries {
    id
    title
    description
    commodity
    region
    location
    isDiscontinued
    order
}

Apollo seems to be classing the return value of the fragment as a union or interface. I don't think adding the IntrospectionFragmentMatcher should be necessary as we have no need of unions or interfaces, although maybe I'm wrong. Adding __typename to the fragment didn't help.

  • How do I remove this error (I may just be missing some gql syntax for typing?)
  • Does using fragments mean we should set up the IntrospectionFragmentMatcher regardless.. (the docs say it should only be needed when using fragments on interfaces or unions which we are not)
  • Is the error a bug, should I just be hiding the error (it does work as is if you ignore it)

Update

ApolloClient is created as follows

 client = new ApolloClient({
      link: createLink('MY_URL', Apollo.fetch),
      cache: new InMemoryCache(),
    });
1
Can you please share the code of creating InMemoryCache instance?Raeesaa
@User97 I've added the code above, its currently got no custom configurationTom
Okay, I don't see any reason for it to throw error in that case as long as ${typename} is passed correctly.Raeesaa
Are you writing directly to cache in your code using writeQuery, writeFragment or writeData? If so, are you omitting writing the __typename when you do so?Daniel Rearden
The error is being thrown when calling `readFragment' so before any write calls. I've tried removing them all and still get the same messageTom

1 Answers

0
votes

You need to create the apollo cache and setup normalization features with dataIdFromObject.

import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  // Here you may want to pass your introspection query result data,
});

const cache = new InMemoryCache({
  dataIdFromObject: o => o.id,
  fragmentMatcher,
});