Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async function attachEvents() {
- const urls={
- "posts":`http://localhost:3030/jsonstore/blog/posts`,
- "comments":`http://localhost:3030/jsonstore/blog/comments`
- }
- const postComments=document.getElementById("post-comments")
- const postBody=document.getElementById("post-body")
- const postTitleRef=document.getElementById("post-title")
- const postsRef=document.getElementById("posts")
- const btnViewPostRef=document.getElementById("btnViewPost")
- const btnLoadPostsRef=document.getElementById("btnLoadPosts")
- btnLoadPostsRef.addEventListener("click", loadPosts)
- btnViewPostRef.addEventListener("click",onView)
- async function loadPosts(){
- const posts=await getPosts()
- postsRef.innerHTML=""
- Object.entries(posts).forEach(async(row)=>{
- const[id,data]=row
- const option= createOption(data)
- postsRef.appendChild(option)
- })
- }
- async function onView(e){
- try{
- const comments = await getComments();
- const posts=await getPosts();
- console.log(comments);
- const id = postsRef.value;
- const text = postsRef.options[postsRef.selectedIndex].text;
- console.log(text);
- console.log(Object.values(posts));
- let post = Object.values(posts).find(post => post.title === text);
- let postDetails = Object.values(comments).filter(c => c.postId === id);
- displayPost(post);
- postDetails.forEach(async(data)=>{
- const comment= createComment(data)
- postComments.appendChild(comment)
- })
- }
- catch(err){
- alert(err.message);
- }
- }
- function displayPost(post){
- postTitleRef.textContent=post.title
- postBody.textContent=post.body
- }
- async function getComments(){
- const response=await fetch(urls.comments)
- if (!response.ok) {
- throw new Error(`Error ${response.status} (${response.statusText})`)
- }
- return await response.json()
- }
- function createOption(data){
- const option=document.createElement("option")
- option.setAttribute("value",`${data.id}`)
- option.id=data.id
- option.textContent=`${data.title}`
- return option
- }
- async function getPosts(){
- const response=await fetch(urls.posts)
- if (!response.ok) {
- throw new Error(`Error ${response.status} (${response.statusText})`)
- }
- return await response.json()
- }
- function createComment(data){
- const li=document.createElement("li")
- li.setAttribute("id",`${data.id}`)
- li.textContent=`${data.text}`
- console.log(li)
- return li
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment