Exercise VII
Exercise: Fetch and Display User Data
Now that we understand promises and async/await
, let's apply these concepts in a real-world scenario.
We'll create a simple application that fetches user data from an API and displays it on the page.
In this example:
- We define an
async
functionloadUserData
to fetch user data from an API. - The fetched data is then used to populate an unordered list in the DOM.
- A button with the ID
loadButton
is used to trigger the data loading.
Objective:
- Learn how to use event handlers to interact with the DOM.
- Practice using
async/await
to handle API calls. - Learn how to manipulate the DOM based on API responses.
Instructions:
-
Set Up the HTML:
- Create an HTML file and add a button with the ID
loadButton
and an empty unordered list with the IDuserList
.
- Create an HTML file and add a button with the ID
html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>User List</title></head><body><button id="loadButton">Load Users</button><ul id="userList"></ul><script src="./dist/exercise7.js"></script></body></html>
- Write the TypeScript:
- Create a TypeScript file named
exercise7.ts
in thesrc
directory and complete the following code:
ts
// exercise7.ts// 1. Write an async function to fetch user data from// https://jsonplaceholder.typicode.com/users// 2. If the fetch call is sucessful update the ul#userList with the user data returned.// If the fecth call fails, alert the user// 3. The function should fire when the user clicks the button with ID #loadButton
Ensure the compiled exercise7.js
file is correctly referenced in your HTML file inside the dist
directory.
-
Test Your Application:
- Open the HTML file in a browser.
- Click the "Fetch User Data" button.
- Observe the user's name, email, and phone number displayed on the page.
Expected Output:
- When the "Fetch User Data" button is clicked, the user's name, email, and phone number should appear on the page.
- If there is an error during the fetch, an error message should be displayed.
Solution:
ts
// app.tsasync functionfetchUserData ():Promise <void> {try {constresponse = awaitfetch ("https://jsonplaceholder.typicode.com/users/1");if (!response .ok ) {throw newError ("Failed to fetch user data.");}constuser = awaitresponse .json ();displayUserData (user );} catch (error ) {if ((error asError ).message ) {document .getElementById ("userData")!.textContent = `Error: ${(error asError ).message }`;}}}functiondisplayUserData (user : {name : string;phone : string;}): void {constuserDataDiv =document .getElementById ("userData")!;userDataDiv .innerHTML = `<h2>${user .name }</h2><p><strong>Email:</strong> ${user .<p><strong>Phone:</strong> ${user .phone }</p>`;}document .getElementById ("fetchButton")?.addEventListener ("click",fetchUserData );