Medium
Optimistic Mutation
The todo app below lets users add new tasks. The mutation works correctly, but after clicking "Add", there is a noticeable delay before the new item appears in the list — the UI waits for the server round-trip. Your task: 1. Add an optimisticResponse to the useMutation call so the UI updates instantly. 2. Include the correct __typename fields in the optimistic response. 3. Implement an update callback to write the new todo into the cache. The mutation returns: { addTodo { id text completed __typename } }
Problem Code
import React, { useState } from 'react';import { useQuery, useMutation, gql } from '@apollo/client';const GET_TODOS = gql`query GetTodos {todos {idtextcompleted}}`;const ADD_TODO = gql`mutation AddTodo($text: String!) {addTodo(text: $text) {idtextcompleted}}`;const TodoApp = () => {const [newTodo, setNewTodo] = useState('');const { data, loading } = useQuery(GET_TODOS);// Bug: no optimistic response — UI feels slowconst [addTodo] = useMutation(ADD_TODO, {refetchQueries: [{ query: GET_TODOS }],});const handleAdd = () => {if (!newTodo.trim()) return;addTodo({ variables: { text: newTodo } });setNewTodo('');};if (loading) return <p>Loading...</p>;return (<div><h1>Todo List</h1><inputvalue={newTodo}onChange={(e) => setNewTodo(e.target.value)}placeholder="Add a todo..."/><button onClick={handleAdd}>Add</button><ul>{data?.todos.map((todo: { id: string; text: string; completed: boolean }) => (<li key={todo.id}>{todo.text}</li>))}</ul></div>);};export default TodoApp;
App.tsx