Mutations: Creating Links

In this section, you’ll learn how you can send mutations with Apollo. It’s actually not that different from sending queries and follows similar steps that were mentioned before with queries:

  1. Write the query as a JS constant using the gql parser function
  2. use apollo to call the mutation through the mutate method

Preparing the VueJS components

Like before, let’s start by writing the VueJS component where users will be able to add new links.

This is a standard setup for a VueJS 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 data and will be used in createLink when the mutation is sent.

Writing the Mutation

But how can you now actually send the mutation? Let’s follow the three steps from before.

First you need to define the mutation in your graphql constants file and parse your query with gql. 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:

  1. You first create the JavaScript constant called CREATE_LINK_MUTATION that stores the mutation.
  2. Now you define the actual GraphQL mutation. It takes two arguments, url and description, that you’ll have to provide when calling the mutation.

Let’s see the mutation in action!

As promised, all you need to do is call this.$apollo.mutate and pass the mutation and the variables that represent the user input.

You should now see the following screen:

Two input fields and a submit-button - not very pretty, but functional.

Enter some data into the fields, e.g.:

  • Description: The best learning resource for GraphQL
  • URL: 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’ll see the following server response:

{
  "data": {
    "allLinks": [
      // ...,
      {
        "description": "The best learning resource for GraphQL",
        "url": "www.howtographql.com"
      }
    ]
  }
}

Awesome! The mutation works, great job! 💪

Unlock the next chapter
How do you execute a GraphQL mutation within a VueJS component?
Add a mutation property to the component
Add a mutation property to the component's apollo object
Call this.$apollo.mutate within a method
You can not execute a mutation within a VueJS component