Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use useMutation hook to trigger GraphQL mutations with Apollo React Hooks

    Tomasz ŁakomyTomasz Łakomy
    reactReact
    apolloApollo
    graphqlGraphQL

    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

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.