Updating arrays in state
Toggle watched on a list of shows by mapping to a new array, not by mutating.
The watchlist is now an array in state. Change one card with
Array Methods map, and give each row a key from
Rendering a list of shows.
Mutate the array and the badges stay put
shows[0].watched = true edits the array React already has.
setShows(shows) passes the same identity, so The Bear's pill never
appears.
Andor starts with a pill. Tick The Bear. That still stays empty.
map to a copy
map returns a new array. Copy the item you change as well, with the
same spread as the last lesson.
setShows(
shows.map((show) =>
show.id === id ? { ...show, watched: !show.watched } : show
)
);
Tick The Bear. Its pill appears. Andor stays watched.
Adding or removing
[...shows, newShow] adds a card. filter drops one. Do not sort here.
Press Drop Andor. Two cards remain. filter handed React a new array.
Common mistakes
shows.push. That mutates the old array. Spread ormapinstead.- Flipping
show.watchedthen returning that same object frommap. Copy the item:{ ...show, watched: !show.watched }. - Forgetting the key. Use a stable
id, as Rendering a list of shows covers.
Exercise
The checkboxes mutate each show in place, so ticks do nothing on screen. Andor already starts watched.
Fix the toggle. Tick The Bear and Severance: both stills show a Watched pill. Andor keeps its pill from the first paint.
Hint: map to a new array, and spread the item you change.