Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Save Data With localStorage

Sam’s recipe box forgot every recipe added since the page loaded, because each load runs main.js from the top, and main.js starts with the same five recipes. In this video, you saved the recipes in localStorage, first the wrong way, then as JSON text. Here are the key points:

  • localStorage is a small store of text that the browser keeps through both a reload and closing the browser. There’s one store per origin: the start of the address, up to the number after the colon, such as http://127.0.0.1:3000. Its setItem() method saves a value under a name, called a key. Every page at that origin shares the store, so pick a key that names your app, such as "recipe-box".
  • The Application panel in DevTools shows what the browser keeps for a page. Open DevTools and pick the Application tab (if it’s hidden, it’s under the » menu). In the sidebar, under Storage, expand Local storage and pick your page’s origin, such as http://127.0.0.1:3000. The table shortens long values, so select a row to see its whole value below the table, where DevTools lays out JSON as a tree you can expand.
  • localStorage keeps only strings, so setItem() turns anything else into a string first. Handing it the recipes array as it is saves the array’s items joined with commas, and an object turned into a string only says that it’s an object, so every recipe becomes the same text, [object Object]. The names, servings and minutes never reach the store.
  • The getItem() method reads the value saved under a key. After that first attempt, it gives back the same [object Object] text, and JSON.parse() throws a SyntaxError on it, because it was never JSON. The recipes can’t come back from it.
  • Save JSON text instead. Wrap the array in JSON.stringify(), so setItem() gets JSON text with every recipe’s fields. The old [object Object] text stays in the store until the next save, and each setItem() call replaces the whole value under its key.
  • Save after every change to the array: right after the form pushes a new recipe, and right after a delete.
  • Watch out: a saved value comes back as a string. Even a number saved on its own, such as 6, comes back as the text '6', so adding 1 to it gives '61', not 7, unless you convert the text to a number first.
  • Nothing reads the save yet. After a reload, the store still holds all six recipes, but the list shows five, because main.js builds the list from its own five recipes.

Inside setUpRecipeBox() in recipes/main.js, add saveRecipes(), and call it in the submit listener and in the Delete dialog’s close listener. The rest of the file is unchanged:

Language: JavaScript Filename: recipes/main.js
function saveRecipes() {
  localStorage.setItem("recipe-box", JSON.stringify(recipes));
}

form.addEventListener("submit", (event) => {
  // ...read the form, as before
  recipes.push({ ... });
  saveRecipes();
  render();
  // ...as before
});

dialog.addEventListener("close", () => {
  // ...as before
  const [recipe] = recipes.splice(index, 1);
  saveRecipes();
  render();
  // ...as before
});

Add a recipe, such as Pea and mint soup, then open the Application panel and select the recipe-box row. It holds the six recipes as JSON text, with Pea and mint soup last.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In the last lesson, you turned Sam’s recipes into JSON text. That text sat in a variable, though, so a reload still wipes it. In this video, you’ll save the recipes somewhere that survives a reload.

00:13 Here’s the problem on Sam’s page. Sam adds a pea and mint soup, and the list grows to six. Then Sam reloads the page, and the soup is gone. Every load runs main.js from the top, and main.js starts with the same five recipes.

00:32 The browser keeps a small store of text called localStorage, which survives both a reload and closing the browser. There’s one store per origin: the start of the address, up to the number after the colon.

00:46 The store’s setItem method saves a value under a name, called a key. Every page at that origin shares the store, so pick a key that names this app, such as recipe-box.

00:59 You know the store holds text. So what does it do with an array? Here’s a first attempt that seems reasonable. It’s a detour, and the way it fails shows how the store works.

01:10 A new function, saveRecipes, hands the recipes array to setItem as it is. The form’s listener calls it right after it pushes the new recipe.

01:21 Add the pea and mint soup again. To see what was saved, open DevTools and pick the Application tab, under the double-arrow menu if it’s hidden. This panel shows what the browser keeps for a page.

01:33 In its sidebar, under Storage, expand Local storage, and pick the entry for the page’s origin. A key called recipe-box is there. Select its row, and the whole value shows below the table.

01:47 It’s [object Object], six times, with commas between. When setItem gets anything but a string, it turns it into a string first. An array becomes its items, joined with commas.

02:01 And an object turned into a string only says that it’s an object, so every recipe becomes the same text. The names, servings and minutes never reached the store.

02:14 You can confirm this in the Console. The getItem method reads the value saved under a key, and here it gives back that same text. Hand that text to JSON.parse, and it throws a SyntaxError right away.

02:28 It was never JSON, so the recipes can’t come back from it. You already have the tool that writes data as text. In saveRecipes, wrap the array in JSON.stringify, so setItem gets JSON text.

02:45 Call saveRecipes after a delete too, so every change to the array is saved.

02:51 Once the page reloads with the new code, the old text is still in the store, because nothing has saved since. The next setItem replaces the whole value. So add the soup one more time.

03:04 Now the value is JSON text, and the preview lays out all six recipes, names and all. Watch out: a saved value comes back as a string. Even the number six, saved on its own, comes back as the text six, so adding one gives sixty-one, not seven.

03:24 Now reload the page one more time. The store still holds all six recipes, with the pea and mint soup last. Your turn: pause the video and predict how many recipes the list will show.

03:40 It shows five. The soup is still in the store, but main.js builds the list from its own five recipes, and nothing in it reads the save yet.

03:52 As a rule: localStorage keeps only strings, so turn your data into JSON text before you save it, under one key, after every change. Sam’s recipes now reach the store, but the page doesn’t use them yet.

04:07 Next, in Load Saved Data on Every Visit, you’ll read the save back each time the page loads.

Become a Member to join the conversation.