Remembering the Tickets

Book a seat and click Run: your ticket is gone, and the seat is free again. State lives only while the app runs. To keep the tickets, you need localStorage, and you already have a hook for it: useLocalStorage is in the file useLocalStorage.js, as you wrote it in the lesson Refs and Custom Hooks. It works like useState, and on top of that, it saves the value under a key and starts with what's saved there. So one line in Showtimes changes:

const [tickets, setTickets] = useLocalStorage("tickets", []);

That's all. The picker still gets the tickets in its props, and the list Your tickets still shows them: neither needs to know where the tickets come from. Taken seats stay taken, and Your tickets keeps its tickets after Run too. In the preview, the console's Clear saved data button deletes them.

Why the key tickets, when the old site saved its bookings under bookings? Our tickets look different: they keep the whole showtime, where the old bookings had only its showtimeId. Once your React app is online at the old site's address, it gets the same localStorage in your browser, with any bookings you made while you tried out the old site. Under the key bookings, the app would read them as tickets, find no ticket.showtime in them and stop with an error. Under a new key, the app starts with nothing saved.

Canceling. A booking you no longer want should be easy to cancel. Each ticket gets a Cancel button, and handleCancel(id) makes a new array without that ticket, with filter(), as in the exercise Removing from an Array. The hook saves the new array, and the seats are free again.

Instructions

  1. In Showtimes.jsx, import the hook (import useLocalStorage from "./useLocalStorage.js";) and create tickets with it, as above. Book a seat and click Run: the ticket is still in the list, and the seat is taken.

  2. In each li of Your tickets, put the text into a span, and after it a button Cancel, for example with the classes cursor-pointer text-sm font-semibold text-red-700 hover:underline. Its click calls handleCancel(ticket.id), which removes the ticket from tickets. To put the button at the right end of the ticket, give the li the classes flex items-center justify-between gap-4 as well.