React
Boost Your React Apps with Apollo: Beyond the Basics

Solution: Updating the Cache after Deleting a Habit

Mute
Current Time 0:00
/
Duration Time 0:00
Loaded: 0%
Progress: 0%
Stream TypeLIVE
Remaining Time -0:00
 
PRO

How'd it go? Hopefully the hint I gave you in the exercise video helped. Instead of using the options object in the hook, we can use it in the function.

First, we need to delete that options object from the hook:

// src/Habit.js
const [deleteHabit, { error, loading }] = useMutation(DELETE_HABIT);

Then, down in the onClick handler for the delete button, we'll pass the options object to deleteHabit. This is where we can create the update function. In the update function, we'll read the habits with readQuery and filter out the deleted habit with writeQuery.

Here's the finished onClick handler:

// src/Habit.js
onClick={() => {
  const habitIdToDelete = habit.id;
  deleteHabit({
    variables: { id: habitIdToDelete },
    update: (cache, { data }) => {
     const { habits } = cache.readQuery({ query: HABITS_QUERY });
     cache.writeQuery({
        query: HABITS_QUERY,
        data: { habits: habits.filter((habit) => habit.id !== habitIdToDelete), },
    });
  },
 });
}}
 

I finished! On to the next chapter