In Keep Old Saves Working, Sam’s loadRecipes() learned to sort the saves it finds: nothing saved, damaged text, a version-1 save, or a version-2 save, with the starter recipes and a message for anything it can’t use. Saving got much less attention. saveRecipes() still assumes that the browser always accepts what it’s given and keeps it for good.
In this lesson, you’ll make the box tell Sam when a save fails and keep the page working when the browser refuses to store anything. You’ll also find out how long a successful save really lasts and why the box saves after every change.
Tell Sam When a Save Fails
The browser’s store isn’t endless, and the call to setItem() is where you find that out. Chrome gives each origin room for 5,242,880 characters, about 5 million, counting keys and values together.
Open Sam’s recipe box at http://127.0.0.1:3000/recipes/index.html through Live Preview, with its Console open, and ask for more than that. The repeat() method builds a string of six million copies of "x":
localStorage.setItem("recipe-box.test", "x".repeat(6_000_000));
Chrome refuses, and the Console shows the error in red:
Uncaught QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting the value of 'recipe-box.test' exceeded the quota.
The setItem() call threw a QuotaExceededError and stored nothing, so localStorage.getItem("recipe-box.test") still gives null.
Sam’s six recipes take about 1,500 characters, so the box alone would need thousands of recipes to fill its store. However, that limit belongs to the whole origin. As you saw in Load Saved Data on Every Visit, Live Preview serves every project in your editor’s folder from one origin, and another app’s large save can leave no room for Sam’s.
To see what Sam would see, fill the store almost to the brim. First, add Pea and mint soup with 4 servings, 25 minutes, Soup selected, and Vegetarian checked, so the box has a save. Then run these lines in the Console:
let used = 0;
for (const entry of Object.entries(localStorage)) {
used += entry[0].length + entry[1].length;
}
const left = 5_242_880 - used;
localStorage.setItem("filler", "x".repeat(left - 10));