There are two top-level operation types in GraphQL: queries and mutations.
Queries are used when we want to read data.
Mutations are used when we want to change data. We use mutations when we want to create, update, or delete records.
In this section, we’ll learn how to send mutations with Apollo. Doing so is actually not that much different than sending queries and follows similar steps.
gql
parser functionuseMutation
hook provided by Apollo Client to
send mutations to our GraphQL serverLike 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 held in the component’s
local state by way of the useState
hook.
Our job now is to take the user input and send it as arguments in a GraphQL mutation.
First, we need to define the mutation in our JavaScript code
and use the useMutation
hook to fire the mutation.
When we use the useMutation
hook, we need to destructure
out a function that can be used to call the mutation. That’s
what createLink
is in the code block above. We’re now free
to call the function whenever we need to when the component
renders.
We’re now ready to check wether the mutations are working.
Now, when we run yarn start
, we should see the following:
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
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 the query here
{
feed {
links {
description
url
}
}
}
You’ll see the following server response:
{
"data": {
"feed": {
"links": [
// ...
{
"description": "The best learning resource for GraphQL",
"url": "howtographql.com"
}
]
}
}
}
Awesome! The mutation works, great job! 💪