Use GraphQL Mutations in Vue 3 with the useMutation Composable

Share this video with your friends

Social Share Links

Send Tweet

The form can update state locally but changes don't persist. We need to take the mutation we wrote in GraphiQL and use it in our Vue app.

Using the useMutation composable, we pass it our gql and an arrow function that returns the variables. The variables are assigned to our updateFields object's properties.

After destructuring an update function off of useMutation, we define a handleSubmit function and call our update function inside. Then, we emit a close event and prevent the default behavior of the form.

Instructor: [0:00] Let's take this mutation and use it in our Vue application. In our update-craft form, we're going to have updateMutation. It's going to be a GQL, and what we just created in GraphQL. We need to import gql from @apollo/client/core, and then we're going to need to import useMutation from our @vue/apollo-composable.

[0:27] Now I want to use my useMutation function, so I'm going to destructure the mutate function, which I'm going to alias to update-craft. I'm destructuring that from the useMutation function that takes as its first argument the mutation that we've defined up above. We call that updateMutation. Brilliant.

[0:46] The second argument is a function that needs to return an object. That object has a key of variables, and then an object of all the variables that we want to consider. The ID is going to be, for the update fields, the ID, the name, the updateFields.name, and so on, for the other fields. It needs to be an integer, so we just want to make sure that that's a number.

[1:14] When we click the Update button, we want to do two things. We want to mutate and then we want to emit a close event. Let's create a function for that. Let's handle the submit, and let's go take an event.

[1:26] The first thing we want to do, we want to await our updateCraft function, and then we want to emit close. Back in our form, the first thing we do is, when we submit, we want to prevent the browser default, which would refresh the page. Instead, when we've got our button, on click, we want to handle our submit with that.

[1:44] Let's see. In our boat here, we can see the age is at zero months. Let's change that to be 10. Update. I've sent my update, my API is updated, and if I refresh the page now, my frontend is going to be updated. Update, change it to 100, so we can see this stays 10. When I refresh the page, the API data has correctly been updated.