Advertisement
bebo231312312321

Untitled

Jun 24th, 2023
107
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.     async function onPost(e) {
  7.         posts.innerHTML = ""
  8.         try {
  9.             const response = await fetch(`http://localhost:3030/jsonstore/blog/posts`)
  10.             if (!response.ok) throw new Error()
  11.             const data = await response.json()
  12.  
  13.             Object.entries(data).forEach(([key, value]) => {
  14.                 let optionElement = document.createElement('option')
  15.                 optionElement.value = key, optionElement.textContent = value.title
  16.                 posts.appendChild(optionElement)
  17.             })
  18.         } catch (err) {
  19.             console.log(`${err}`)
  20.         }
  21.     }
  22.    
  23.     async function onView(e) {
  24.         try{
  25.             comments.innerHTML = "";
  26.             let select = [...posts.children].find((x) => x.selected == true)
  27.             const res = await fetch(`http://localhost:3030/jsonstore/blog/posts/${select.value}`)
  28.             if (!res.ok) throw new Error()
  29.             const data = await res.json()
  30.             document.getElementById('post-title').textContent = data.title
  31.             document.getElementById('post-body').textContent = data.body
  32.    
  33.             const comment = await fetch(`http://localhost:3030/jsonstore/blog/comments`)
  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.         }catch(err){
  45.             console.log(err)
  46.         }
  47.     }
  48. }
  49.  
  50. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement