Saving the List

Add an item and click Run again. The item is gone: when a page opens, its script starts from the beginning, and the list loads from the file again. In a real browser, the same would happen every time you closed the page or reloaded it. A shopping list that forgets what you put on it isn't much use, so in this exercise, it will remember.

As you know from the lesson on data from a server, a page can keep data in the browser, in localStorage, and the data stays there even when the page is closed. localStorage stores only text, so the array goes in as JSON: JSON.stringify() turns it into text, and JSON.parse() turns the text back into an array of objects. The list is saved under the key "items":

// Saves the list in the browser
function saveItems() {
    localStorage.setItem("items", JSON.stringify(items));
}

The list has to be saved every time it changes. So far, it changes in two places: in the handler of the Add button, which adds an item, and in the handler of each item, which crosses it off. Call saveItems() in both, right after the change.

When the page opens, loadItems() first looks for a saved list. localStorage.getItem() returns null when nothing has been saved under the key yet, for example the first time the page opens. When there is a saved list, the function shows it and ends with return, so it loads the file only when nothing has been saved:

const saved = localStorage.getItem("items");
if (saved !== null) {
    items = JSON.parse(saved);
    showItems();
    return;
}

Here, the preview keeps what the page saves while you work on the exercise. Once something is saved, the console shows a button, Clear saved data, which opens the page again as if for the first time, with nothing saved.

Typical mistakes:

  • Saving the array without JSON.stringify(). localStorage then holds the text [object Object],[object Object], and when the page opens, JSON.parse() fails with a SyntaxError. Fix the code and click Clear saved data, so that the page stops loading the broken text.
  • A different key in setItem() and getItem(), such as "items" and "list". The page then never finds what it saved.

Instructions

Below showItems(), write the function saveItems() from above. Call it in the handler of the Add button right after push(), and in the handler of the items right after item.bought changes.

At the start of loadItems(), add the code from above that loads the saved list. Try it: add an item, cross one off and click Run. The list stays as you left it. To start again from the file, click Clear saved data.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

7/9

Next