Remembering Bookings
Book a few seats and click Run. The seats are free again, as if nothing had happened: the bookings were only in the variable bookings, and with every run, the script starts from the beginning, just as it does when a visitor opens the page again.
A real cinema keeps its bookings on its server, where the bookings of all visitors come together: a seat booked by one visitor is taken for everyone else. That needs a program that runs on the server, which is a topic of its own. Your page keeps the bookings in the browser, in localStorage, as in the lesson Data from a Server. The visitor then finds their bookings when they come back.
You know how: after each change, save the array as JSON text with JSON.stringify(), and when the page opens, read it back with JSON.parse(), if anything is saved:
let bookings = [];
const savedBookings = localStorage.getItem("bookings");
if (savedBookings !== null) {
bookings = JSON.parse(savedBookings);
}showSeats() already looks for taken seats in bookings, so the saved bookings show as taken seats as soon as they're loaded. In the preview, the console's Clear saved data button deletes them, and the seats are free again.
Typical mistakes:
- Saving the array before the new booking is added to it. After a reload, the newest booking is missing.
- Saving the array without
JSON.stringify(). It's saved as text such as[object Object], and when the page opens again,JSON.parse()ends with aSyntaxError.
Instructions
- 1
After each booking, save the array
bookingsinlocalStorageunder the keybookings, as JSON text. - 2
When the page opens, load the saved bookings, if there are any. Book a few seats and click Run: they stay taken.