Search code examples
graphqlnuxt.jsapollovue-apollo

Invariant Violation: Expecting a parsed GraphQL document


I'm getting the following error despite the mutation being wrapped in the gql tag:

Invariant Violation: Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? http://docs.apollostack.com/apollo-client/core.html#gql

This issue is only caused by the mutation code below, I have a query that works.

Code:

<script>
import gql from 'graphql-tag'

export default {
  apollo: {
    createTask: {
      mutation: gql`
        mutation Task(
          $taskName: String!
          $taskDesc: String!
        ) {
          setSession(
            taskName: $taskName
            taskDesc: $taskDesc
          ) {
            id
            taskName
          }
        }
      `,
      variables() {
        return {
          taskName: this.res.data.task_name,
          taskDesc: this.res.data.task_description,
        }
      },
    },
  },
  data() {
    return {
      createTask: '',
    }
  },
}
<script>

Solution

  • Smart queries are declared using the apollo object and are ran when the component mounts. If you have queries that you'd like to run this way, then your code would look something like this:

    export default {
      apollo: {
        someQuery: gql`...`,
      }
    }
    

    However, when working with mutations, you generally don't want to run them on mount. Instead, you want to execute the mutation in response to some user action, like a button click. So the above syntax won't work for mutations. Instead, you need to call this.$apollo.mutate directly inside one of your methods:

    export default {
      methods: {
        createTask() {
          this.$apollo.mutate({
            mutation: gql`...`,
            variables: {...},
            // other options
          }).then(result => {
            // do something with the result
          })
        }
      }
    }