Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL mutation: Invariant Violation: Must contain a query definition

Tags:

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!

like image 800
Siddhartha Chowdhury Avatar asked Mar 16 '19 22:03

Siddhartha Chowdhury


People also ask

What is the difference between query and mutation in GraphQL?

While we use queries to fetch data, we use mutations to modify server-side data. If queries are the GraphQL equivalent to GET calls in REST, then mutations represent the state-changing methods in REST (like DELETE , PUT , PATCH , etc).

What does mutation mean in GraphQL?

In GraphQL, you insert, update or delete data with mutations. A Mutation is a GraphQL Operation that allows you to insert new data or modify the existing data on the server-side. You can think of GraphQL Mutations as the equivalent of POST , PUT , PATCH and DELETE requests in REST.

How are HTTP requests sent ApolloClient authenticated?

Luckily, Apollo provides a nice way for authenticating all requests by using the concept of middleware, implemented as an Apollo Link. import { setContext } from '@apollo/client/link/context'; This middleware will be invoked every time ApolloClient sends a request to the server.


1 Answers

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       }     }`, }) 
like image 127
Daniel Rearden Avatar answered Oct 23 '22 08:10

Daniel Rearden