Skip to content

Commit 6055b0a

Browse files
committed
Fetch - with async/await
1 parent 97ebd9b commit 6055b0a

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

app.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,10 @@ const url = "./api/people.json";
66

77
const btn = document.querySelector(".btn");
88

9-
btn.addEventListener("click", () => {
10-
fetch(url)
11-
.then((response) => response.json())
12-
.then((data) => {
13-
// console.log(data);
14-
displayPeople(data);
15-
})
16-
.catch((error) => console.log(error));
9+
btn.addEventListener("click", async () => {
10+
const response = await fetch(url);
11+
const data = await response.json();
12+
displayPeople(data);
1713
});
1814

1915
const displayPeople = (people) => {

references/fetch-example.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Fetch built-in
2+
// promised based
3+
// XHR is not wrong, you can complete all our upcoming examples and projects using XHR. Fetch is just alternative approach that has simpler and cleaner syntax. The end result is the same.Still get dynamically, behind the scenes.
4+
5+
const url = "./api/people.json";
6+
7+
const btn = document.querySelector(".btn");
8+
9+
btn.addEventListener("click", () => {
10+
fetch(url)
11+
.then((response) => response.json())
12+
.then((data) => {
13+
// console.log(data);
14+
displayPeople(data);
15+
})
16+
.catch((error) => console.log(error));
17+
});
18+
19+
const displayPeople = (people) => {
20+
const displayData = people
21+
.map((person) => {
22+
const { name } = person;
23+
return `<p>${name}</p>`;
24+
})
25+
.join("");
26+
const element = document.createElement("div");
27+
element.innerHTML = displayData;
28+
document.body.appendChild(element);
29+
};

0 commit comments

Comments
 (0)