Advertisement
bebo231312312321

Untitled

Jun 26th, 2023
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function attachEvents() {
  2.     let selectMenu = document.getElementById('posts');
  3.     let postBody = ''
  4.     document.getElementById('btnLoadPosts').addEventListener('click', async () => {
  5.         let posts = await fetch('http://localhost:3030/jsonstore/blog/posts');
  6.         let postsData = await posts.json();
  7.         selectMenu.innerHTML = "";
  8.         for (let post of Object.values(postsData)) {
  9.             selectMenu.add(new Option(post.title, post.id));
  10.             postBody= post.body
  11.         }
  12.     });
  13.     document.getElementById('btnViewPost').addEventListener('click', async () => {
  14.         let selectMenu = document.getElementById('posts');
  15.         let postComments = document.getElementById('post-comments');
  16.         let postTitle = document.getElementById('post-title');
  17.         let commentPara = document.getElementById('post-body');
  18.         postComments.innerHTML = "";
  19.         let [body,comments] = await Promise.all([
  20.             fetch(`http://localhost:3030/jsonstore/blog/posts/` +selectMenu.value),
  21.             fetch('http://localhost:3030/jsonstore/blog/comments'),
  22.         ]);
  23.       let [bodyText,commentsData] = await Promise.all([body.json(),comments.json()]);
  24.       postTitle.textContent = selectMenu.options[selectMenu.selectedIndex].text;
  25.       commentPara.textContent = postBody;    
  26.          const comm = Object.values(commentsData).filter(c => c.postId == selectMenu.value)
  27.         .forEach(x=>{
  28.             let li = document.createElement('li');
  29.             li.id = x.postId;
  30.             li.textContent = x.text;
  31.             postComments.appendChild(li);
  32.         })
  33.     });
  34.  }
  35. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement