Medium
Reactive Local State
The bookstore app below lets users favorite books. Currently, favorites are stored in component-level useState, so they are lost whenever the user navigates away and comes back. Your task: 1. Replace useState with a reactive variable (makeVar) that persists across component mounts. 2. Use useReactiveVar to read the reactive variable in the component. 3. Add the @client directive to a local-only GraphQL field (optional bonus) or simply use the reactive variable directly. The favorites should persist as long as the Apollo Client instance is alive (no page reload needed).
Problem Code
import React, { useState } from 'react';import { useQuery, gql } from '@apollo/client';const GET_BOOKS = gql`query GetBooks {books {idtitleauthorcoverUrl}}`;const BookStore = () => {// Bug: favorites lost on navigation/re-mountconst [favorites, setFavorites] = useState<string[]>([]);const { data, loading } = useQuery(GET_BOOKS);const toggleFavorite = (bookId: string) => {setFavorites((prev) =>prev.includes(bookId)? prev.filter((id) => id !== bookId): [...prev, bookId]);};if (loading) return <p>Loading books...</p>;return (<div><h1>Bookstore</h1><div>{data?.books.map((book: { id: string; title: string; author: string; coverUrl: string }) => (<div key={book.id}><img src={book.coverUrl} alt={book.title} /><h3>{book.title}</h3><p>{book.author}</p><button onClick={() => toggleFavorite(book.id)}>{favorites.includes(book.id) ? '★ Unfavorite' : '☆ Favorite'}</button></div>))}</div><h2>Favorites ({favorites.length})</h2></div>);};export default BookStore;
App.tsx