Use useMutation hook to trigger GraphQL mutations with Apollo React Hooks

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

GraphQL is fantastic not only for querying data, but also for mutating it and with Apollo React Hooks we're able to do both.

In this lesson we're going to learn how to use useMutation hook in order to add an item to a todo list with hooks instead of using the render props pattern based Mutation component

Instructor: [0:00] We have an app connected to this GraphQL endpoint over here, which allows us to query to-dos. What we would like to do is to be able to add a new to-do to this list. In our React app, we have defined a mutation that we would like to trigger whenever a user is going to click on the add to-do button.

[0:14] In order to do that, we need to implement this onSubmit handler over here. First, import useMutation from Apollo React Hooks. Next, we need to destructure addToDo, we're going to get data as well from useMutation, and we're going to pass in the addToDo mutation like this.

[0:32] Next up, we need to call this addToDo function. We're going to call it with an argument which is an object. We're going to pass in some variables, and the variables are going to be of type input.value. After I save and refresh that, I think we have the desired effect.

[0:47] If I add in a to-do, "Hello, this is a test," and I click on add to-do. Now, if I go to playground and query this endpoint again, we're going to see this "Hello, this is a test" to-do added to the list.