Items from a File

Until now, the starting items have been written right in script.js. Apps usually keep their data apart from the code, in a file or on a server, and load it when the page opens. Your list will do the same. Its starting items are now in the file items.json, in the third tab of the editor. They're the ones from the array, plus coffee, so that you'll see when the list comes from the file.

You know how to load a file from the lesson on data from a server. fetch() asks for it, and the answer arrives a moment later, so an async function waits for it with await. response.ok says whether the file was found, and await response.json() turns its JSON into an array of objects, just like the one in items:

async function loadItems() {
    const response = await fetch("items.json");
    items = await response.json();
    showItems();
}

The function puts a new array into items, and a constant can't get a new value, so create items with let now. It starts as an empty array, [], because the list is empty until the file arrives.

Why does loadItems() call showItems() itself? Because the items are there only after the await. The code after loadItems(); at the end of the script runs right away, before the file arrives, so a showItems() there would show an empty list.

Loading takes a moment: a third of a second in the preview, several seconds on a slow connection. Meanwhile, a good app says what's going on. And if the file can't be loaded, it says that too, instead of just showing an empty list.

Typical mistakes:

  • Keeping const items. The console then shows TypeError: Assignment to constant variable.
  • Forgetting await before response.json(). items then holds a Promise instead of the array, and showItems() ends with TypeError: items is not iterable.

Instructions

Change items to an empty array that can change: let items = [];. Below showItems(), write the function loadItems() from above. At the end of the script, call loadItems() instead of showItems(). After a moment, the page shows four items, coffee among them, and To pay: €16.

At the start of loadItems(), show Loading… in message. Once the items have arrived, clear the message again (message.textContent = "").

If the file can't be loaded (response.ok is false), show The list couldn't be loaded. in message and end the function with return, before response.json(). Try it: change the name in fetch() to itemz.json, a file that doesn't exist, and run the code. Then change it back.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/9

Next