React
Boost Your React Apps with Apollo: Beyond the Basics

Updating Apollo's Cache after Adding a Habit

PRO

Even though updating the cache is the default for updating a single item, it's not for adding or deleting items. Let's learn how to update the cache after adding a habit.

To do this, we need to provide our mutation with an update function.

In that function, we first need to read the current list of habits from the cache using readQuery. Then, we can add the new habit we get back from the createHabit mutation to the cache using writeQuery. Here's how that looks:

// src/AddHabit.js
const [createHabit, { error, loading }] = useMutation(CREATE_HABIT_MUTATION, {
    update: (cache, { data: { createHabit } }) => {
      // read data from cache
      const { habits } = cache.readQuery({ query: HABITS_QUERY });
      // update the cache with new data
      cache.writeQuery({
        query: HABITS_QUERY,
        data: { habits: habits.concat([createHabit]) },
      });
    },
  });

When you run the client, you should now only see one call to the server: creating the habit. The list of habits will magically update!

I highly recommend reading more about readQuery and writeQuery in the docs.