-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
64 lines (57 loc) · 1.83 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const usersUl = document.querySelector("#users");
const url = "https://jsonplaceholder.typicode.com/users";
const displayPosts = (posts, userId) => {
const userPostsDiv = document.querySelector(`#user-posts${userId}`);
const userPostsUl = userPostsDiv.querySelector("ul");
posts.forEach((post) => {
const li = document.createElement("li");
li.innerHTML = `
<h4>${post.title}</h4>
<p>${post.body}</p>
`;
userPostsUl.appendChild(li);
});
userPostsDiv.classList.remove("hidden");
const hideBtn = userPostsDiv.querySelector("#hide-posts");
hideBtn.addEventListener("click", () => {
userPostsDiv.classList.add("hidden");
});
};
const handleFetchPosts = () => {
const getButtons = document.querySelectorAll(".btn-get-posts");
getButtons.forEach((btn) => {
btn.addEventListener("click", (e) => {
const userId = btn.getAttribute("id");
fetch(`${url}/${userId}/posts`)
.then((res) => res.json())
.then((posts) => {
displayPosts(posts, userId);
})
.catch((error) => console.log("error while fetching posts: ", error));
});
});
};
fetch(url)
.then((res) => res.json())
.then((data) => {
data?.map((user) => {
const li = document.createElement("li");
li.innerHTML = `
<div>
<span>${user.name}</span>
<span>${user.email}</span>
<button class="btn-get-posts" id="${user.id}">Get ${user.name}'s Posts</button>
</div>
<div class="hidden" id="user-posts${user.id}">
<ul id="user-posts-ul">
<li id="hide-posts">Hide</li>
</ul>
</div>
`;
li.classList.add("user-li");
li.classList.add("content");
usersUl.appendChild(li);
});
handleFetchPosts();
})
.catch((error) => console.log("error while fetching users: ", error));