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
Published 5 years ago
Updated 3 years ago

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.

egghead
egghead
~ 8 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today