Medium
Cache Surgery
The contact manager below lets users delete contacts. The mutation fires successfully and the server removes the contact, but the deleted item still appears in the list until the page is refreshed. Your task: 1. After the delete mutation succeeds, remove the deleted contact from the Apollo cache. 2. Use cache.evict to remove the item by its cache ID, or use cache.modify on the ROOT_QUERY. 3. Call cache.gc() to garbage-collect any orphaned references. The mutation returns: { deleteContact { id } }
Problem Code
import React from 'react';import { useQuery, useMutation, gql } from '@apollo/client';const GET_CONTACTS = gql`query GetContacts {contacts {idnamephone}}`;const DELETE_CONTACT = gql`mutation DeleteContact($id: ID!) {deleteContact(id: $id) {id}}`;const ContactList = () => {const { data, loading } = useQuery(GET_CONTACTS);// Bug: no cache update after deletion — stale data persistsconst [deleteContact] = useMutation(DELETE_CONTACT);const handleDelete = (id: string) => {deleteContact({ variables: { id } });};if (loading) return <p>Loading contacts...</p>;return (<div><h1>Contacts</h1><ul>{data?.contacts.map((contact: { id: string; name: string; phone: string; email: string }) => (<li key={contact.id}><span>{contact.name} — {contact.phone}</span><button onClick={() => handleDelete(contact.id)}>Delete</button></li>))}</ul></div>);};export default ContactList;
App.tsx