Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const [postBtn, posts, viewBtn, comments] = ['#btnLoadPosts', '#posts', "#btnViewPost", '#post-comments']
- .map(sel => document.querySelector(sel))
- postBtn.addEventListener('click', onPost)
- viewBtn.addEventListener('click', onView)
- async function onPost(e) {
- posts.innerHTML = ""
- try {
- const response = await fetch(`http://localhost:3030/jsonstore/blog/posts`)
- if (!response.ok) throw new Error()
- const data = await response.json()
- Object.entries(data).forEach(([key, value]) => {
- let optionElement = document.createElement('option')
- optionElement.value = key, optionElement.textContent = value.title
- posts.appendChild(optionElement)
- })
- } catch (err) {
- console.log(`${err}`)
- }
- }
- async function onView(e) {
- try{
- comments.innerHTML = "";
- let select = [...posts.children].find((x) => x.selected == true)
- const res = await fetch(`http://localhost:3030/jsonstore/blog/posts/${select.value}`)
- if (!res.ok) throw new Error()
- const data = await res.json()
- document.getElementById('post-title').textContent = data.title
- document.getElementById('post-body').textContent = data.body
- const comment = await fetch(`http://localhost:3030/jsonstore/blog/comments`)
- const dataComments = await comment.json()
- Object.values(dataComments).forEach((el) => {
- if (data.id === el.postId) {
- let li = document.createElement('li')
- li.textContent = el.text
- li.id = el.id
- comments.appendChild(li);
- }
- });
- }catch(err){
- console.log(err)
- }
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement