-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.js
51 lines (50 loc) · 1.37 KB
/
blog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let postsArray = []
const titleInput = document.getElementById("post-title")
const bodyInput = document.getElementById("post-body")
const form = document.getElementById("new-post")
function renderPosts() {
let html = ""
for (let post of postsArray) {
html += `
<h3>${post.title}</h3>
<p>${post.body}</p>
<hr />
`
}
document.getElementById("blog-list").innerHTML = html
}
// getting data
fetch("https://apis.scrimba.com/jsonplaceholder/posts")
.then(res => res.json())
.then(data => {
postsArray = data.slice(0, 5)
renderPosts()
})
// post button created and submi
form.addEventListener("submit", function(e) {
e.preventDefault()
const postTitle = titleInput.value
const postBody = bodyInput.value
const data = {
title: postTitle,
body: postBody
}
// adding a new data with post
const options = {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
}
//adding data on top
fetch("https://apis.scrimba.com/jsonplaceholder/posts", options)
.then(res => res.json())
.then(post => {
postsArray.unshift(post)
renderPosts()
titleInput.value = ""
bodyInput.value = ""
// form.reset()
})
})