georgiev955

06. Posts

Oct 30th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. async function attachEvents() {
  2. const postsRes = await fetch('http://localhost:3030/jsonstore/blog/posts');
  3. const posts = await postsRes.json();
  4. const commentsRes = await fetch('http://localhost:3030/jsonstore/blog/comments');
  5. const comments = await commentsRes.json();
  6.  
  7. const btnLoadPosts = document.getElementById('btnLoadPosts');
  8. const btnViewPost = document.getElementById('btnViewPost');
  9. const selectMenu = document.getElementById('posts');
  10.  
  11. btnLoadPosts.addEventListener('click', loadPostsOptions);
  12. btnViewPost.addEventListener('click', viewPostDetails);
  13.  
  14. function loadPostsOptions() {
  15. selectMenu.innerHTML = '';
  16. for (const post in posts) {
  17. const title = posts[post].title
  18. const id = post;
  19. const optionEl = document.createElement('option');
  20. optionEl.id = id;
  21. optionEl.textContent = title;
  22. selectMenu.appendChild(optionEl);
  23. }
  24. }
  25.  
  26. function viewPostDetails() {
  27. const selectedIndex = selectMenu.selectedIndex;
  28. const selectedOption = selectMenu.options[selectedIndex];
  29. const id = selectedOption.id;
  30. const title = selectMenu.value;
  31. const body = posts[id].body;
  32.  
  33. document.getElementById('post-title').textContent = title;
  34. document.getElementById('post-body').textContent = body;
  35.  
  36. const commentsUl = document.getElementById('post-comments');
  37. const commentsArr = Object.values(comments).filter(x => x.postId === id);
  38. commentsArr.forEach(line => {
  39. const currentComment = line.text;
  40. const litElement = document.createElement('li');
  41. litElement.textContent = currentComment;
  42. commentsUl.appendChild(litElement);
  43. })
  44. }
  45. }
  46. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment