I am trying to implement a graphQL API, it went well with queries but it's going not that well with mutations:
Here is my basic mutation using apollo-client
and graphql-tag
:
import gql from 'graphql-tag'
const addNewPlace = (place) => {
return client.mutate({
mutation: gql`
mutation {
addNewPlace(
input: {
$title: String!
}
) {
place { title }
}
}
`,
variables: {
title: place.title
}
})
}
Here I was trying to use variables. When changing the mutation to look like that one below, it is going smoothly however, it's not the right way to do id.
const addNewPlace = (place) => {
return client.mutate({
mutation: gql`
mutation {
addNewPlace(
input: {
title: "${place.title}"
}
) {
place { title }
}
}
`
})
}
Any idea where I made my mistake?
When using variables, there's three steps you need to take:
Add the variables to the request being sent. In Apollo, it's done by specifying a variables
property inside the object you pass to mutate
. You wrote:
variables: { title: place.title }
This is fine. We are sending some variable, called title, with whatever value, along with the request to our server. At this point, GraphQL doesn't even know about the variables.
Declare your variables inside your operation. You don't have to name your operation, but it's good practice to do so:
mutation AddNewPlace($title: String) {
Here, we are telling GraphQL we've included a variable called title. You could call it anything (foo for example), as long as it matched what you passed to the variables prop in #1. This step is important because A) GraphQL needs to know about the variable and B) it needs to know what type of variable you are passing in.
Finally, include the variable in your mutation, like this:
addNewPlace(input: { title: $title }) {
Be careful not to mix up your variable definition in step #2 with your input definition in step #3. Also, I'm assuming your typeDefs include some kind of input
type like AddNewPlaceInput. Rather than passing in just title, you can pass in an object like this:
variables: { input: { title: place.title } }
Then your mutation looks like this:
mutation AddNewPlace($input: AddNewPlaceInput) {
addNewPlace(input: $input) {
# fields returned by the mutation
I would highly recommend enabling a GraphiQL endpoint so you can easily test your queries and mutations before implementing them on the client side.
Lastly, you may want to check and make sure the fields you are asking for in the mutation match your type definition. I'm just guessing here, but if your mutation resolves to a Place type, you wouldn't need to put place { title }
, just title
, unless your Place type actually has a place
field.