<button type="button" class="btn">Fetch users</button>
<ul class="user-list"></ul>
body {
margin: 16px;
line-height: 1.5;
color: #212121;
font-family: sans-serif;
}
p {
margin: 0;
}
.user-list {
margin: 0;
list-style: none;
padding: 24px;
}
.user-list li:not(:last-child) {
margin-bottom: 16px;
}
const fetchUsersBtn = document.querySelector(".btn");
const userList = document.querySelector(".user-list");
fetchUsersBtn.addEventListener("click", () => {
fetchUsers()
.then((users) => renderUsers(users))
.catch((error) => console.log(error));
});
function fetchUsers() {
return fetch(
"https://jsonplaceholder.typicode.com/users?_limit=7&_sort=name"
).then((response) => {
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
});
}
function renderUsers(users) {
const markup = users
.map((user) => {
return `
<li>
<p><b>Name</b>: ${user.name}</p>
<p><b>Email</b>: ${user.email}</p>
<p><b>Company</b>: ${user.company.name}</p>
</li>
`;
})
.join("");
userList.insertAdjacentHTML("beforeend", markup);
}
This Pen doesn't use any external JavaScript resources.