← Back to the exercise

Updating objects in state

The answer to the exercise in Updating objects in state.

show.year = show.year + 1 edited the object React already held, so setShow(show) looked like nothing changed. A spread copy is a new object, and the year updates.

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

export default function App() {
  const [show, setShow] = useState({
    title: "The Bear",
    year: 2022,
    genre: "Drama",
    rating: { average: 8.6 },
    network: { name: "FX" },
    still: "still-warm",
  });

  function handleYear() {
    setShow({ ...show, year: show.year + 1 }); // was: mutate, then setShow(show)
  }

  return (
    <div className="page">
      <ShowCard show={show} onYear={handleYear} />
    </div>
  );
}