Loading lessons...
Project 5: Data from an API
Project 5: Data from an API
Fetch real data from an API and display it on the page using async/await.
Step 1: The HTML
<button id="load">Load users</button>
<ul id="userList"></ul>
<p id="status"></p>
Step 2: The JavaScript
const list = document.getElementById("userList");
const status = document.getElementById("status");
document.getElementById("load").addEventListener("click", loadUsers);
async function loadUsers() {
try {
status.textContent = "Loading...";
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
list.innerHTML = "";
users.forEach(function(user) {
const li = document.createElement("li");
li.textContent = user.name;
list.appendChild(li);
});
status.textContent = "Loaded " + users.length + " users.";
} catch (err) {
status.textContent = "Request failed: " + err.message;
}
}
Step 3: How it works
fetchrequests the data.await response.json()parses the JSON.forEachbuilds a list item per user.- try/catch handles network failures.
Step 4: Make it yours
Change the URL to any public API you like and display different data.
Bonus ideas
- Show a loading spinner.
- Add a search box to filter results.
- Display user emails as well.
TL;DR
- fetch + await gets data from an API.
- response.json() parses the reply.
- Build page content with createElement and appendChild.
- Wrap requests in try/catch.