Advertisement
bebo231312312321

Untitled

Jun 24th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     const [postBtn, posts, viewBtn, comments] = ['#btnLoadPosts', '#posts', "#btnViewPost", '#post-comments']
  3.         .map(sel => document.querySelector(sel))
  4.  
  5.     postBtn.addEventListener('click', onPost)
  6.     viewBtn.addEventListener('click', onView)
  7.     async function onPost(e) {
  8.  
  9.         const response = await fetch(`http://localhost:3030/jsonstore/blog/posts`);
  10.         const data = await response.json();
  11.         posts.innerHTML = "";
  12.         Object.entries(data).forEach(([key, value]) => {
  13.             let optionElement = document.createElement('option');
  14.             optionElement.value = key
  15.             optionElement.textContent = value.title
  16.             posts.appendChild(optionElement)
  17.         })
  18.     }
  19.  
  20.     async function onView(e) {
  21.  
  22.         let select = [...posts.children].find((x) => x.selected == true)
  23.         const [res, comment] = await Promise.all([
  24.             fetch(`http://localhost:3030/jsonstore/blog/posts/${select.value}`),
  25.             fetch(`http://localhost:3030/jsonstore/blog/comments`)
  26.         ]);
  27.         const data = await res.json();
  28.         comments.innerHTML = "";
  29.         document.getElementById('post-title').textContent = data.title
  30.         document.getElementById('post-body').textContent = data.body
  31.         const dataComments = await comment.json();
  32.  
  33.         Object.values(dataComments).forEach((el) => {
  34.             if (data.id == el.postId) {
  35.                 let li = document.createElement('li')
  36.                 li.textContent = el.text
  37.                 li.id = el.id
  38.                 comments.appendChild(li);
  39.             }
  40.         });
  41.     }
  42. }
  43.  
  44. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement