← Back to the exercise

Updating arrays in state

The answer to the exercise in Updating arrays in state.

The handler mutated a show inside the old array, then passed that same array back. map builds a new list, and { ...show, watched: !show.watched } builds a new item for the one you ticked.

import { useState } from "react";
import "./styles.css";
import ShowCard from "./ShowCard";

const start = [
  { id: "s1", title: "The Bear", year: 2022, genre: "Drama", rating: 8.6, still: "still-warm", watched: false },
  { id: "s2", title: "Severance", year: 2022, genre: "Thriller", rating: 8.7, still: "still-cold", watched: false },
  { id: "s3", title: "Andor", year: 2022, genre: "Sci-Fi", rating: 8.4, still: "still-dusty", watched: true },
];

export default function App() {
  const [shows, setShows] = useState(start);

  function handleToggle(id) {
    setShows(
      shows.map((show) =>
        show.id === id ? { ...show, watched: !show.watched } : show
      )
    );
  }

  return (
    <div className="page">
      {shows.map((show) => (
        <ShowCard key={show.id} show={show} onToggle={handleToggle} />
      ))}
    </div>
  );
}