Keep Old Saves Working

In Catch Only What You Can Handle, Sam’s loadRecipes() learned to survive a damaged save. A small try around JSON.parse() catches a SyntaxError and rethrows anything else. But a save can also parse perfectly and still break the box because older code wrote it.

In Follow a Path Into Nested Data, you followed paths into recipes with ingredients written out. Now Sam’s real box gets them, and its old saves don’t have them. You’ll add them and watch what that does to an older save. Then you’ll put a version number in the save, upgrade old saves as they load, and fall back with a message when a save can’t be used. Start with a save from an older copy of Sam’s app.

Give Each Recipe Its Ingredients

Sam wants each recipe to carry its ingredients. First, though, put an old save in the store. Open Sam’s recipe box at http://127.0.0.1:3000/recipes/index.html through Live Preview, with its Console open. If you’re joining the course here, 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 starterRecipes = [
  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),
];

function loadRecipes() {
  const savedText = localStorage.getItem("recipe-box");
  let saved;
  try {
    saved = JSON.parse(savedText);
  } catch (error) {
    if (error instanceof SyntaxError) {
      console.log(`Damaged save: ${error.message}`);
      return starterRecipes;
    }
    throw error;
  }
  return saved ?? starterRecipes;
}

const recipes = loadRecipes();

// 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);

Sam has a second copy of the box on the kitchen laptop. It runs an older version of the app, from before the form converted servings with Number(), so its two recipes have their servings as text, such as "4". To put the same save in your browser, run this in the Console:

Language: JavaScript
const oldSave = [
  {
    id: "5b0e4a7c-2f61-4d8e-9a3b-7c1d2e6f8a90",
    name: "Sunday roast chicken",
    servings: "4",
    minutes: 90,
    category: "main",
    vegetarian: false,
  },
  {
    id: "e3c9d1f2-8a47-4b6c-b5e0-2d9f7a1c4e36",
    name: "Banana bread",
    servings: "8",
    minutes: 70,
    category: "baking",
    vegetarian: true,
  },
];
localStorage.setItem("recipe-box", JSON.stringify(oldSave));

This replaces whatever was saved under "recipe-box", including Sam’s six recipes from the last lesson. Reload, and the box lists the laptop’s two recipes, Sunday roast chicken (serves 4, 90 min), main and Banana bread (serves 8, 70 min), baking, vegetarian. Today’s code reads the old save without complaint.

Now add the ingredients, a list of { name, amount, unit } objects per recipe. In recipes/main.js, give the recipe() helper a sixth parameter, items, stored as ingredients:

Language: JavaScript
function recipe(name, servings, minutes, category, veg, items) {
  return {
    id: crypto.randomUUID(),
    name,
    servings,
    minutes,
    category,
    vegetarian: veg,
    ingredients: items,
  };
}

Then replace starterRecipes with this version, where each call passes the recipe’s ingredients as the sixth argument:

Language: JavaScript
const starterRecipes = [
  recipe("Grandma Ines's lentil soup", 6, 45, "soup", true, [
    { name: "lentils", amount: 200, unit: "g" },
    { name: "onion", amount: 1, unit: "whole" },
    { name: "stock", amount: 1, unit: "l" },
  ]),
  recipe("Sunday roast chicken", 4, 90, "main", false, [
    { name: "chicken", amount: 1, unit: "whole" },
    { name: "potatoes", amount: 800, unit: "g" },
    { name: "onion", amount: 2, unit: "whole" },
  ]),
  recipe("Banana bread", 8, 70, "baking", true, [
    { name: "bananas", amount: 3, unit: "whole" },
    { name: "flour", amount: 250, unit: "g" },
  ]),
  recipe("Weeknight fried rice", 2, 20, "main", false, [
    { name: "rice", amount: 300, unit: "g" },
    { name: "eggs", amount: 2, unit: "whole" },
    { name: "onion", amount: 1, unit: "whole" },
  ]),
  recipe("Lemon drizzle cake", 10, 60, "dessert", true, [
    { name: "lemons", amount: 2, unit: "whole" },
    { name: "sugar", amount: 200, unit: "g" },
  ]),
];

Two more changes finish the job. In rowText(), add a line right above return text; that shows how many ingredients a recipe has:

Language: JavaScript
    text += `, ${recipe.ingredients.length} ingredients`;

A recipe added through the form has no ingredients yet, so in the submit listener, add ingredients: [] to the object that recipes.push() receives, after vegetarian: data.has("vegetarian"),.

That’s the change most programmers would make, but the store still holds the laptop’s save. Save main.js, and the list is empty, with an error in the Console, followed by its stack trace:

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.