React
Boost Your React Apps with Apollo: Fetching & Updating Data

Use the Mutation in the UI

PRO

Now that we've figured out our mutation, let's add this feature to the UI.

First, we'll import the AddHabit component I've provided for you into App.js:

import AddHabit from "./AddHabit";

Then, we can use that component below our total points:

<AddHabit />

The AddHabit component is pretty straightforward. It uses a ref to get the text input and then an event handler calls setDescription from useState. Our challenge is to use that description piece of state in the input for the createHabit mutation.

We'll do all of this in AddHabit.js. First, let's import useMutation and gql from Apollo:

import { useMutation, gql } from "@apollo/client";

Next, we'll add the mutation above the component:

const CREATE_HABIT_MUTATION = gql`
  mutation CREATE_HABIT_MUTATION($input: NewHabitInput) {
    createHabit(input: $input) {
      id
      description
      points
      entries {
        id
        notes
        date
        completed
      }
    }
  }
`;

Then, we'll use the useMutation hook inside of the component:

const [createHabit, { error, loading }] = useMutation(CREATE_HABIT_MUTATION);

This means we can now call createHabit in the addHabit function that gets called when the user presses enter or clicks the "Add Habit" button:

const addHabit = (e) => {
  e.preventDefault();
  const input = { description };
  createHabit({ variables: { input } });
  descriptionInput.current.value = "";
  setDescription("");
};

Note that, to pass variables into the mutation, we'll need to provide an object with a variables key that is also an object. This "object soup" can get a little confusing, so hang in there. It helps to look at the useMutation API docs to see what's going on there.

Up next, I'll hand this off to you with an exercise to improve the UI.

 

I finished! On to the next chapter