-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (57 loc) · 1.79 KB
/
index.js
File metadata and controls
64 lines (57 loc) · 1.79 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
60
61
62
63
64
const BASE_URL = 'http://localhost:3000';
function main() {
displayPosts();
addNewPostListener();
}
async function displayPosts() {
const res = await fetch(`${BASE_URL}/posts`);
const posts = await res.json();
const listDiv = document.getElementById('post-list');
listDiv.innerHTML = '';
posts.forEach(post => {
const el = document.createElement('div');
el.className = 'post-item';
el.dataset.id = post.id;
el.innerHTML = `
<img src="${post.image_url}" alt="${post.title}" width="50" />
<strong>${post.title}</strong>
`;
el.addEventListener('click', () => handlePostClick(post.id));
listDiv.appendChild(el);
});
// Optional: display details of first post on load
if (posts.length > 0) handlePostClick(posts[0].id);
}
async function handlePostClick(id) {
const res = await fetch(`${BASE_URL}/posts/${id}`);
const post = await res.json();
const detailDiv = document.getElementById('post-detail');
detailDiv.innerHTML = `
<h2>${post.title}</h2>
<p><em>by ${post.author}</em></p>
<img src="${post.image_url}" alt="${post.title}" width="200" />
<p>${post.content}</p>
`;
}
function addNewPostListener() {
const form = document.getElementById('new-post-form');
form.addEventListener('submit', async e => {
e.preventDefault();
const { blog, kimanzi, content } = form.elements;
const newPost = {
blog: title.value,
kimanzi: author.value,
content: content.value,
image_url: 'https://via.placeholder.com/150'
};
// Display immediately on frontend:
await fetch(`${BASE_URL}/posts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newPost)
});
form.reset();
displayPosts();
});
}
document.addEventListener('DOMContentLoaded', main);