import { useEffect, useState } from 'react'; import { Alert, Box, Card, CardContent, Grid, IconButton, Skeleton, Tooltip, Typography, } from '@mui/material'; import FavoriteIcon from '@mui/icons-material/Favorite'; import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder'; import { api } from '../api'; import { useAuth } from '../AuthContext'; export default function Browse() { const { user } = useAuth(); const [quotes, setQuotes] = useState(null); const [favoriteIds, setFavoriteIds] = useState(new Set()); const [error, setError] = useState(''); useEffect(() => { api.list().then(setQuotes).catch((err) => setError(err.message)); }, []); useEffect(() => { if (!user) { setFavoriteIds(new Set()); return; } api .favorites() .then((rows) => setFavoriteIds(new Set(rows.map((r) => r.id)))) .catch(() => setFavoriteIds(new Set())); }, [user]); async function toggleFavorite(quoteId) { if (!user) return; const isFav = favoriteIds.has(quoteId); try { if (isFav) { await api.removeFavorite(quoteId); } else { await api.addFavorite(quoteId); } setFavoriteIds((prev) => { const next = new Set(prev); isFav ? next.delete(quoteId) : next.add(quoteId); return next; }); } catch (err) { setError(err.message); } } return ( Browse quotes {error && ( setError('')}> {error} )} {quotes === null && Array.from({ length: 6 }).map((_, i) => ( ))} {quotes?.map((q) => ( “{q.text}” — {q.author} toggleFavorite(q.id)} > {favoriteIds.has(q.id) ? ( ) : ( )} ))} ); }