Write a GraphQL Mutation using React Hooks with Urql

Ian Jones
InstructorIan Jones

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 months ago

We look at how to use useMutation from urql to run a GraphQL mutation query.

useMutation accepts a Graphql mutation as a string and passes the result and function to execute the query back in an array. This function can be called as many times as you like, passing variables the GraphQL query has defined.

Instructor: [0:00] The first thing we need to do is import Use Mutation from URQL. Next, we're going to call Use Mutation, which Use Mutation returns an array. The first element in the array is the result, the result of the query that we are going to execute.

[0:28] The second element in the array is the Execute Mutation function. It's the function that we will run to call the query, so equals Use Mutation.

[0:43] Now we need to pass out our query which we haven't defined yet. We'll call ours Add Course, then up above, we'll define our Add Course query. It's a mutation, we'll call it Add Course. We want the slug, which is a string. We want the title, which is also a string.

[1:24] The query that we have defined on our GraphQL server is called Insert Courses. It takes objects and those objects having slug, slug and title is the title. Next, we need to define what we want the query to return. This query has a returning attribute which will grab the title and slug.

[2:07] Now that we have our Add Course mutation defined, we need to call Execute Mutation and pass it a slug and a title. Inside of our onClick, we will call Execute Mutation with an object of Slug is Course and title will be Course!

[2:49] Let's go above the return block and log the result of this query. If we open up our dev tools, go to the console, the result is data is undefined, errors undefined, and fetching is false because we haven't clicked it.

[3:14] Once we clicked the button, the second result will be fetching is true, and the third result will be fetching is false. Here's our data. Insert courses, returning, and then our actual data.

[3:38] If I click this again, we'll get an error because we have a unique constraint on the slug. Since we tried to add a course with New Course slug, again our API returned an error shown here.

[4:00] We can guard against this by checking if-rest.error then we can return "Oh, no." Once we click this, we'll get an error, and now we have "Oh, no."

[4:24] To recap, we import Use Mutation from URQL. We call Use Mutation and pass it our query which is defined here. This URQL hook returns a result in the first spot of the array and the Execute Mutation in the second spot.

[4:45] We then pass the Execute Mutation function to our onClick button handler to fire off a new request, handling any errors if they happen.