Advertisement
bebo231312312321

Untitled

Jun 26th, 2023
193
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.     postBtn.addEventListener('click', onPost)
  5.     viewBtn.addEventListener('click', onView)
  6.     let postBody = '';
  7.     async function onPost(e) {
  8.         const response = await fetch(`http://localhost:3030/jsonstore/blog/posts`);
  9.         const data = await response.json();
  10.         posts.innerHTML = "";
  11.         Object.entries(data).forEach(([key, value]) => {
  12.             let optionElement = document.createElement('option');
  13.             optionElement.value = key
  14.             optionElement.textContent = value.title
  15.             posts.appendChild(optionElement)
  16.             postBody = value.body
  17.         })
  18.     }
  19.     async function onView(e) {
  20.         let select = [...posts.children].find((x) => x.selected == true)
  21.         const [res, comment] = await Promise.all([
  22.             fetch(`http://localhost:3030/jsonstore/blog/posts/${select.value}`),
  23.             fetch(`http://localhost:3030/jsonstore/blog/comments`)
  24.         ]);
  25.         const data = await res.json();
  26.         comments.innerHTML = "";
  27.         document.getElementById('post-title').textContent = posts.options[posts.selectedIndex].text
  28.         document.getElementById('post-body').textContent = postBody
  29.         const dataComments = await comment.json();
  30.  
  31.         Object.values(dataComments).forEach((el) => {
  32.             if (data.id == el.postId) {
  33.                 let li = document.createElement('li')
  34.                 li.textContent = el.text
  35.                 li.id = el.id
  36.                 comments.appendChild(li);
  37.             }
  38.         });
  39.     }
  40. }
  41. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement