34

I am trying to make a mutation call to my graphQL server from a react application. The react code looks like the following:

client.query({
  query: gql`
    mutation{
        addTeam(input:{name:"Somename", label:"somelabel"})
        {error, status}
    }`
 }).then((resp: any) => {
      console.log("Success", resp);
 }).catch(err => {
      throw err;
 })

And I am getting the following error:

enter image description here

But if I change the same request, from mutation to query, and make the necessary changes in my node-graphQL-server to handle it as query instead of mutation the same code works.

Apollo-Client Mutation docs says

In GraphQL, mutations are identical to queries in syntax, the only difference being that you use the keyword mutation instead of query...

Oh and BTW, the same mutation query WORKS in Playground. Please help guys, my work is kinda stopped coz of this issue.

Thanks!

Community
  • 1
  • 1
Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46

3 Answers3

96

You should use the mutate method of the client for mutations, not the query method. The options for the method can be found in the docs. Apollo is opinionated about how queries and mutations are treated, so each method has different options that are appropriate to each operation's behavior (for example, mutate includes a refetchQueries option).

client.mutate({
  mutation: gql`
    mutation {
      addTeam(input:{name:"Somename", label:"somelabel"}) {
        error
        status
      }
    }`,
})
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thank you so much, I didn't realize that I was user "client.query" for mutation. +1 – Siddhartha Chowdhury Mar 16 '19 at 22:53
  • 2
    Jeez! "client.mutate"... who knew? – anthony galligani Jun 10 '20 at 20:47
  • This answer solved my problem, but can this be done with a single `gql` string as opposed to the `mutation` object (where `mutation` is used twice)? I'm using the `@rest` call from the [Apollo Client docs](https://www.apollographql.com/docs/link/links/rest/). They use a `gql` query string, followed by a `client.query({ query })` api call. Curious if that's possible with the same inputs that you used here. – Farid Sep 03 '20 at 18:23
  • 1
    your doc link no longer works, could you update it please? – Morgan Smith Feb 23 '21 at 15:18
1

There is currently a GitHub issue that speaks of this error: https://github.com/apollographql/apollo-client/issues/1539

Jstngoulet
  • 1,055
  • 7
  • 12
0

This usually happens when one names their query constant different from query or mutation

e.g.

const query1 = gql`
  query GetPost {
    id
    title
  }
`
const result = await apolloClient.query(query: query1)
Realms AI
  • 101
  • 4