Search code examples
apollo

Getting "Invariant Violation" error with Apollo GraphQL


I'm using Apollo GraphQL but I'm new to it and I'm getting the following error:

{
    "framesToPop": 1,
    "name": "Invariant Violation"
}

Here is my code:

const httpLink = createHttpLink({
    uri: "https://api.example.com/v3/ListingsQuery",
    fetch
});
const automaticPersistedQueryLink = createPersistedQueryLink();
const apolloClient = new ApolloClient({
    link: ApolloLink.from([automaticPersistedQueryLink, httpLink]),
    cache: new InMemoryCache()
});
const variables = {
    filters: {statuses: ["ACTIVE", "UNLISTED"]},
    orderBys: [{sortField: "STATUS", sortOrder: "DESC"}],
    shouldFetchHostMultiListingAgendaPermissions: true,
    offset: 0,
    shouldFetchListingPermissions: false,
    count: 15,
    query: null
};
await apolloClient.query({
    query: {},
    variables
});

Any idea what I'm doing wrong?


Solution

  • First of all, it appears that Apollo is being started in "production mode" rather than "developement mode". By starting it in development mode, Apollo would provide you more detailed error messages. To fix this, start your node process with env.NODE_ENV set to development. Sorry if this is not clear, but I can't be more precise here, as the exact procedure depends on how your application is being started and/or which framework you are using...

    Still, in recent versions, you should have a numeric error code in the error message when run in production mode, such as Invariant Violation: 42. These numeric error codes makes it easier to diagnose problems, even in production mode. Make sure you are using a recent version of @apollo/client (latest is 3.2.5 at the time I'm writing this; see https://www.npmjs.com/package/@apollo/client).

    Now, regarding the error itself... The full error message is most likely Invariant Violation: You must wrap the query string in a "gql" tag. It is due to the fact that you are providing an empty query, as shown below:

    await apolloClient.query({
        query: {},   // <--- Empty query here
        variables
    });
    

    There are several ways to provide queries to the Apollo client. The simplest way to do so is to embed your GraphQL query in the JavaScript source code, using the "gql tag" notation, such as this:

    await apolloClient.query({
        query: gql`
          query TestQuery {
            launch(id: 56) {
              id
              mission {
                name
              }
            }
          }
        `,
        variables
    });
    

    This should work out of the box, but for performance reason, you should add a GraphQL compilation step in your build process. Maybe this process is already in place (for example, if you are started your project using a framework such as Create React Apps or Gatsby...). See this document for explanations on this (https://www.apollographql.com/docs/react/performance/babel/).