Drawing the Page from Data

Fetched data is usually an array of objects, and the page shows it the way you know from the lesson on web pages: a function clears the list and creates elements for the items in a loop. What's new is where the array comes from. Keep it in a variable outside the functions, so that the page can be drawn again whenever the user changes something, without asking the server again:

let books = [];

function showBooks() {
    bookList.textContent = "";
    const available = books.filter((book) => book.available);
    for (const book of available) {
        const item = document.createElement("li");
        const title = document.createElement("h2");
        title.textContent = book.title;
        const author = document.createElement("p");
        author.textContent = book.author;
        item.append(title, author);
        bookList.append(item);
    }
}

async function loadBooks() {
    const response = await fetch("books.json");
    books = await response.json();
    showBooks();
}

loadBooks();

A few things to notice:

  • books is outside the functions, created with let and an empty array. loadBooks() puts the fetched array in it, and showBooks() draws the page from it. Once the data is there, any other function can use it too.
  • filter() returns a new array and leaves books as it is, so all the books are there again for the next drawing. The other array methods, such as sort(), find() and map(), work on fetched data as on any other array.
  • Each item has elements inside it: a heading and a paragraph. Create them with createElement() too, and put them into the item with append(), which can take several elements at once.

When the user chooses something on the page, its handler only calls showBooks() again. The function reads what's chosen and draws the list anew. The server isn't asked again: the data is already in the array.

Instructions

Complete showAnimals(): clear animalList, and for each animal in animals, append an li to it with two elements inside: an h2 with the animal's name and a p with text like dog, 3 years old.

Make the choice in speciesSelect work. In showAnimals(), pick with filter() only the animals whose species is the value of speciesSelect, or all of them when the value is "all". And when the value of the select changes (the change event), call showAnimals() again.

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