Summary
In this lesson, you learned that:
- A server is a computer on the internet that keeps the files of a website and sends them to whoever asks. A page can ask it for data, too.
- Data travels as text, usually in JSON. It looks like arrays and objects in JavaScript, but keys and text are always in double quotes, there's no comma after the last item, and there are no comments. Files with JSON end in
.json. JSON.parse(text)turns JSON text into arrays and objects;JSON.stringify(value)turns them into JSON text.await fetch("animals.json")asks the server for a file and waits for the response;await response.json()reads its content as JSON. Both belong in anasyncfunction, and the data can be used only after them.response.okisfalsewhen the server answered with an error, such as 404 Not Found for a misspelled file name. Check it, and show an error message instead of the data.- A message such as
Loading…tells the user that the data is on its way. Show it beforefetch(), and remove it when the data is on the page. - Keep fetched data in a variable, and draw the page from it with a function that you call again whenever something changes, with
createElement()and the array methods. localStoragekeeps data in the browser, even after a reload:setItem(key, value)saves,getItem(key)reads (nullwhen nothing is saved) andremoveItem(key)deletes.localStoragekeeps only text, so save arrays and objects withJSON.stringify()and read them withJSON.parse(). Load what was saved as soon as the page opens.
In the next lesson, a checkpoint, you'll build a small app for choosing a film for a film night: it loads the films from a file, lets you search them and remembers your favorites.
But first, some practice: a page of recipes with a checkbox that shows only the vegetarian ones, and that remembers whether it's ticked.
Instructions
Load recipes.json and show each recipe in recipeList as Pancakes (20 min). While the recipes are loading, show Loading… in message, and empty it once they're shown.
When vegetarianCheckbox is ticked, show only the vegetarian recipes, and when it's unticked, all of them again. Keep the recipes in a variable, and draw the list with a function.
Remember the checkbox: when it changes, save in localStorage whether it's ticked, and when the page opens, tick it if it was ticked, so that the list shows only the vegetarian recipes. Tip: JSON.stringify() and JSON.parse() work for true and false too.