-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (39 loc) · 1.12 KB
/
index.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
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;
}
fetch("https://apis.scrimba.com/jsonplaceholder/posts")
.then(res => res.json())
.then(data => {
postsArray = data.slice(0, 10);
renderPosts()
});
form.addEventListener("submit", function (e) {
e.preventDefault();
const title = titleInput.value;
const body = bodyInput.value;
const dataPost = { title, body };
const options = {
method: "POST",
body: JSON.stringify(dataPost),
headers: { "Content-Type": "application/json" }
};
fetch("https://apis.scrimba.com/jsonplaceholder/posts", options)
.then(res => res.json())
.then(resPost => {
postsArray.unshift(resPost);
renderPosts();
form.reset();
})
})