Load Saved Data on Every Visit

At the end of Save Data With localStorage, Sam’s six recipes sat in the store as JSON text, yet the reloaded page listed only five. Every load runs main.js from the top, and the script builds the list from its own five recipes without ever looking at the save.

In this lesson, you’ll close that gap. You’ll make the recipe box read its save each time the page loads, fall back to the five starter recipes on a first visit, and keep saving after every change. You’ll also find out where the save lives, which decides who can see it. Start with the question the page has to ask as it loads: Is there a save at all?

Ask the Store for a Save

Before main.js can use a save, it needs to read one, and it has to cope with a browser that has never saved anything. Open Sam’s recipe box at http://127.0.0.1:3000/recipes/index.html through Live Preview, as before, and open its Console with Ctrl+Shift+J or Cmd+Option+J on macOS. If you’re joining the course here, or your copy has drifted, these are Sam’s two files as the last lesson left them:

Save this page as recipes/index.html:

Language: HTML Filename: recipes/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sam's recipe box</title>
</head>
<body>
<h1>Sam's recipe box</h1>
<form id="add-form">
  <label>
    Name
    <input name="name" required>
  </label>
  <label>
    Servings
    <input name="servings" type="number"
      min="1" max="20" required>
  </label>
  <label>
    Minutes
    <input name="minutes" type="number" min="1" required>
  </label>
  <label>
    Category
    <select name="category">
      <option value="soup">Soup</option>
      <option value="main">Main</option>
      <option value="baking">Baking</option>
      <option value="dessert">Dessert</option>
    </select>
  </label>
  <label>
    <input type="checkbox" name="vegetarian">
    Vegetarian
  </label>
  <button>Add recipe</button>
</form>
<p id="status" role="status"></p>
<label>
  Filter
  <input type="search" id="filter">
</label>
<ul id="recipes"></ul>
<dialog id="confirm-delete" aria-labelledby="confirm-text">
  <form method="dialog">
    <p id="confirm-text"></p>
    <button value="keep">Keep it</button>
    <button value="delete">Delete</button>
  </form>
</dialog>
<script type="module" src="main.js"></script>
</body>
</html>

Save this script next to it as recipes/main.js:

Language: JavaScript Filename: recipes/main.js
function recipe(name, servings, minutes, category, veg) {
  return {
    id: crypto.randomUUID(),
    name,
    servings,
    minutes,
    category,
    vegetarian: veg,
  };
}

const recipes = [
  recipe("Grandma Ines's lentil soup", 6, 45, "soup", true),
  recipe("Sunday roast chicken", 4, 90, "main", false),
  recipe("Banana bread", 8, 70, "baking", true),
  recipe("Weeknight fried rice", 2, 20, "main", false),
  recipe("Lemon drizzle cake", 10, 60, "dessert", true),
];

// Name's message for a name that's only spaces.
const noName = "Give the recipe a name.";

// Sam's script: setUpRecipeBox() runs once, as the page
// loads. `recipes` is the box: one record per recipe.
function setUpRecipeBox(document, recipes) {
  const form = document.querySelector("#add-form");
  const list = document.querySelector("#recipes");
  const nameInput = form.querySelector('[name="name"]');
  const filterInput = document.querySelector("#filter");
  const statusLine = document.querySelector("#status");
  const dialog = document.querySelector("#confirm-delete");
  const question = document.querySelector("#confirm-text");
  let filterText = "";
  let pendingButton = null;

  function rowText(recipe) {
    const { name, servings, minutes, category } = recipe;
    let text = `${name} (serves ${servings}, `;
    text += `${minutes} min), ${category}`;
    if (recipe.vegetarian) {
      text += ", vegetarian";
    }
    return text;
  }

  function isShown(recipe) {
    const name = recipe.name.toLowerCase();
    return name.includes(filterText.toLowerCase());
  }

  function render() {
    list.replaceChildren();
    for (const recipe of recipes) {
      if (!isShown(recipe)) {
        continue;
      }
      const row = document.createElement("li");
      row.textContent = rowText(recipe);
      const remove = document.createElement("button");
      remove.className = "delete";
      remove.dataset.recipeId = recipe.id;
      remove.textContent = `Delete ${recipe.name}`;
      row.append(" ", remove);
      list.append(row);
    }
  }

  function isInBox(name) {
    const wanted = name.toLowerCase();
    for (const recipe of recipes) {
      if (recipe.name.toLowerCase() === wanted) {
        return true;
      }
    }
    return false;
  }

  function checkName() {
    const name = nameInput.value.trim();
    if (name === "") {
      nameInput.setCustomValidity(noName);
    } else if (isInBox(name)) {
      nameInput.setCustomValidity(
        `${name} is already in the box.`,
      );
    } else {
      nameInput.setCustomValidity("");
    }
  }

  function saveRecipes() {
    localStorage.setItem("recipe-box", JSON.stringify(recipes));
  }

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const data = new FormData(form);
    const name = data.get("name").trim();
    recipes.push({
      id: crypto.randomUUID(),
      name,
      servings: Number(data.get("servings")),
      minutes: Number(data.get("minutes")),
      category: data.get("category"),
      vegetarian: data.has("vegetarian"),
    });
    saveRecipes();
    render();
    form.reset();
    statusLine.textContent = `${name} added.`;
    nameInput.focus();
  });

  nameInput.addEventListener("input", checkName);

  function countText(count) {
    if (count === 0) {
      return "No recipes shown.";
    }
    if (count === 1) {
      return "1 recipe shown.";
    }
    return `${count} recipes shown.`;
  }

  filterInput.addEventListener("input", () => {
    filterText = filterInput.value;
    render();
    const shown = list.children.length;
    statusLine.textContent = countText(shown);
  });

  document.addEventListener("keydown", (event) => {
    if (dialog.open) {
      return;
    }
    const field =
      event.target.closest("input, textarea, select") ||
      event.target.isContentEditable;
    if (field || event.isComposing) {
      return;
    }
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return;
    }
    if (event.key !== "/") {
      return;
    }
    event.preventDefault();
    filterInput.focus();
  });

  function indexOfRecipe(id) {
    for (let i = 0; i < recipes.length; i++) {
      if (recipes[i].id === id) {
        return i;
      }
    }
    return -1;
  }

  list.addEventListener("click", (event) => {
    const button = event.target.closest(".delete");
    if (button === null) {
      return;
    }
    pendingButton = button;
    question.textContent = `${button.textContent}?`;
    dialog.returnValue = "";
    dialog.showModal();
  });

  dialog.addEventListener("close", () => {
    if (dialog.returnValue !== "delete") {
      return;
    }
    const button = pendingButton;
    const row = button.closest("li");
    const neighbor =
      row.nextElementSibling || row.previousElementSibling;
    const index = indexOfRecipe(button.dataset.recipeId);
    const [recipe] = recipes.splice(index, 1);
    saveRecipes();
    render();
    checkName();
    statusLine.textContent = `${recipe.name} deleted.`;
    if (neighbor === null) {
      nameInput.focus();
    } else {
      const id =
        neighbor.querySelector(".delete").dataset.recipeId;
      const selector = `[data-recipe-id="${id}"]`;
      list.querySelector(selector).focus();
    }
  });

  render();
}

setUpRecipeBox(document, recipes);

In the last lesson, getItem() gave back the text saved under "recipe-box". Now ask it for a key that Sam’s app has never saved, such as "meal-plan". Type this line into the Console of Sam’s page:

Language: JavaScript
localStorage.getItem("meal-plan")

The Console answers with null:

Language: Program Output
<- null

null is how getItem() says there’s nothing under that key. It isn’t an error or an empty string. On Sam’s very first visit, getItem("recipe-box") gives null in the same way. On every visit after a save, it gives JSON text. So the line that loads the recipes has two cases to handle.

Hand JSON.parse() the JSON text, and it builds the array. What does it do with null? Try it:

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

Become a Member to join the conversation.