Quiz: Stuck at Zero

Each ★ should add its band to your favorites, and the heading counts them. But the heading stays at Favorites: 0, however much you click. Click the line with the mistake.

import { useState } from "react";

const bands = [
    { id: 1, name: "Night Trains" },
    { id: 2, name: "Lunar Cats" },
    { id: 3, name: "Owl Choir" },
];

export default function App() {
    const [favorites, setFavorites] = useState([]);

    function handleFavorite(id) {
        const newFavorites = favorites;
        newFavorites.push(id);
        setFavorites(newFavorites);
    }

    return (
        <main>
            <h1>Favorites: {favorites.length}</h1>
            <ul>
                {bands.map((band) => (
                    <li key={band.id}>
                        {band.name}
                        <button onClick={() => handleFavorite(band.id)}>
                            ★
                        </button>
                    </li>
                ))}
            </ul>
        </main>
    );
}

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/13

Next