Advertisement
bebo231312312321

Untitled

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