-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblogSpace.js
50 lines (45 loc) · 1.29 KB
/
blogSpace.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
let postsArray = [];
const postInput = 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://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(data => {
postsArray = data.slice(0, 5);
renderPosts();
});
form.addEventListener("submit", function(e) {
e.preventDefault();
const postTitle = postInput.value;
const postBody = bodyInput.value;
const data = {
title: postTitle,
body: postBody
};
const options = {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
};
fetch("https://jsonplaceholder.typicode.com/posts", options)
.then(res => res.json())
.then(data => {
//console.log(data);
postsArray.unshift({ title: data.title, body: data.body });
renderPosts();
form.reset();
});
});