-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetch.js
More file actions
59 lines (50 loc) · 1.53 KB
/
Copy pathfetch.js
File metadata and controls
59 lines (50 loc) · 1.53 KB
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
52
53
54
55
56
57
58
59
const url = 'http://localhost:3000/posts';
const output = document.getElementById('output');
function fetchdata() {
output.innerHTML = '';
fetch(url)
.then(res => res.json())
.then(
data => data.forEach(smurf => {
output.innerHTML += `<div class="post-item"><li>${smurf.id} ${smurf.title} </li><button onclick="deletePost('${smurf.id}')">Delete</button></div>`;
})
)
.catch(e => console.log(e));
}
fetchdata();
const button = document.getElementById('clear');
function deletePost(id) {
fetch(`${url}/${id}`, {
method: 'DELETE'
})
.then(() => fetchdata())
.catch(e => console.error('Error deleting post:', e));
}
function addPost () {
const newPost = {
title: document.getElementById('title').value,
views: parseInt(document.getElementById('views').value),
likes: parseInt(document.getElementById('likes').value) || 0
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newPost)
})
.then(() => fetchdata())
.catch(e => console.error('Error adding post:', e));
}
// HTTP VERB (GET) (POST,DELETE,PUT)
// SUBPROBLEMS
// create a basic HTML structure
// create a JS file with logic
// find endpoint api
// consume endpoint api
// display data in HTML using an iteration
// make iteration
// create HTML node (id)
// node.innerHTML (+=)
// analyse array of objects structure (wich attributes are available)
// Done ;)