Day121 — WARNING: heuristic fragment matching going on!

Jacky Tsang
2 min readNov 10, 2019

--

I am using GraphQL fragment on union for a project.

e.g.

query {
all_people {
... on Character {
name
}
... on Jedi {
side
}
... on Droid {
model
}
}
}

error occurs

You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types.
Apollo Client will not be able to 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
WARNING: heuristic fragment matching going on!

Workaround (quick and dirty):

client.query({
query: [your query],
fetchPolicy: 'no-cache',
...

Solution:

  1. create codegen.yml at root
# codegen.yml
schema: YOUR_API
overwrite: true
generates:
./fragmentTypes.json:
plugins:
- fragment-matcher

2. install @graphql-codegen/cli

yarn add -D @graphql-codegen/cli
OR
npm i --save-dev @graphql-codegen/cli

3. run npm run gen to generate .json or .js

"scripts": {
...
"gen": "graphql-codegen --config codegen.yml"
},

3. import that json or js

import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from './fragmentTypes.json';

const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData
});
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';

// add fragmentMatcher code from step 2 here

const cache = new InMemoryCache({ fragmentMatcher });

const client = new ApolloClient({
cache,
link: new HttpLink(),
});

reference:

--

--

Responses (2)