I don't know about you, but it's super annoying to me that the habits list doesn't update after I add a habit. Let's fix that!

Apollo makes this really easy for us. There are actually two ways to handle this. We're going to cover something called "refetching" in this lesson. You can think of refetching as the equivalent of doing a GET call to a REST API in the .then() of a promise. The other way to update data after a mutation is using the Apollo cache, and we'll cover that in the next tutorial.

To get started, we first need to export the HABITS_QUERY from App.js so we can refer to it in AddHabit.js:

// App.js
export const HABITS_QUERY = gql`
  query HABITS_QUERY {
    habits {
      id
      description
      points
      entries {
        id
        notes
        date
        completed
      }
    }

    totalPoints {
      points
      totalCompletedEntries
    }
  }
`;

Now, import that in AddHabit.js:

// AddHabit.js
import { HABITS_QUERY } from "./App";

Finally, add refetchQueries to the useMutation hook:

const [createHabit, { error, loading }] = useMutation(CREATE_HABIT_MUTATION, {
    refetchQueries: [{ query: HABITS_QUERY }],
  });

Now when we add a new habit, the habits list automatically refreshes. Pretty easy, right?

Again, it's a great idea to read the docs on the useMutation hook.

 

I finished! On to the next chapter