In this section, you’ll learn how you can send mutations with Apollo. It’s actually not that different from sending queries and follows the same three steps that were mentioned before, with minor (but logical) differences in the last two steps:
gql
parser function<Mutation />
component passing the GraphQL mutation and variables (if needed) as propsrender prop function
Like before, let’s start by writing the React component where users will be able to add new links.
This is a standard setup for a React component with two input
fields where users can provide the url
and description
of the Link
they want to create. The data that’s typed into these fields is stored in the component’s state
and will be used when the mutation is sent.
But how can you now actually send the mutation to your server? Let’s follow the three steps from before.
First you need to define the mutation in your JavaScript code and wrap your component with the graphql
container. You’ll do that in a similar way as with the query before.
Let’s take a closer look again to understand what’s going on:
POST_MUTATION
that stores the mutation.button
element as render prop function
result with <Mutation />
component passing POST_MUTATION
as prop.variables
prop.Let’s see the mutation in action!
As promised, all you need to do is call the function that Apollo injects into <Mutation />
component’s render prop function
inside onClick button’s event.
Now, run yarn start
, you’ll see the following screen:
Two input fields and a submit-button - not very pretty but functional.
Enter some data into the fields, e.g.:
The best learning resource for GraphQL
www.howtographql.com
Then click the submit-button. You won’t get any visual feedback in the UI, but let’s see if the query actually worked by checking the current list of links in a Playground.
You can open a Playground again by navigating to http://localhost:4000
in your browser. Then send the following query:
# Try to write your query here
{
feed {
links {
description
url
}
}
}
You’ll see the following server response:
{
"data": {
"feed": {
"links": [
// ...
{
"description": "The best learning resource for GraphQL",
"url": "www.howtographql.com"
}
]
}
}
}
Awesome! The mutation works, great job! 💪