1 fetch('https://jsonplaceholder.typicode.com/users')
2 .then(function (response) {
3 return response.json();
4 })
5 .then(function (data) {
6 appendData(data);
7 })
8 .catch(function (err) {
9 console.log('error: ' + err);
10 });
11
12 function appendData(data) {
13 var mainContainer = document.getElementById("users");
14 for (var i = 0; i < data.length; i++) {
15 var li = document.createElement("li");
16 li.innerHTML = data[i].username;
17 li.classList.add('item');
18 li.dataset.userId = data[i].id;
19 li.addEventListener('click', (event) => getPosts(event))
20 mainContainer.appendChild(li);
21 }
22
23 }
24
25 function cleanPosts() {
26 var users = document.querySelectorAll('.item ul');
27 for(var i = 0; i < users.length; i++) {
28 if(users[i]) {
29 users[i].style.display = 'none';
30 }
31 }
32 }
33
34 function getPosts(event) {
35
36 var userId = event.target.dataset.userId;
37
38 fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
39 .then(response => response.json())
40 .then(json => renderPosts(json, event.target))
41 }
42
43 function renderPosts(posts, target) {
44 var postsList = target.childNodes[1];
45
46 cleanPosts();
47
48 if(postsList){
49 postsList.style.display = 'block';
50 } else {
51 var list = document.createElement("ul");
52
53 for (var i = 0; i < posts.length; i++) {
54
55 var item = document.createElement("li");
56 var liTitle = document.createElement("strong");
57 var liBody = document.createElement("p");
58
59 liTitle.innerHTML = posts[i].title;
60 liBody.innerHTML = posts[i].body;
61
62 item.appendChild(liTitle);
63 item.appendChild(liBody);
64 list.appendChild(item);
65 }
66
67 target.appendChild(list);
68 }
69
70 }
71