Run
cd 06_PATCH_and_DELETE_Requests/assets
json-server --watch db.json
const commentList = document.querySelector('#comments');
document.querySelector('#refreshList').addEventListener('click', refreshList);
function refreshList() {
commentList.innerHTML = "";
fetch('http://localhost:3000/comments')
.then(res => res.json())
.then(comments => {
comments.forEach(renderComment)
})
}
function renderComment(comment) {
const li = document.createElement('li');
li.dataset.commentId = comment.id;
li.textContent = `${comment.body} `;
const likeBtn = document.createElement('button');
likeBtn.textContent = likeButtonTextFor(comment);
li.append(likeBtn);
likeBtn.addEventListener('click', (e) => addLike(comment));
commentList.append(li);
}
function addLike(comment) {
fetch(`http://localhost:3000/comments/${comment.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({likes: comment.likes + 1})
})
.then(res => res.json())
.then(comment => {
const btn = document.querySelector(`#comments li[data-comment-id="${comment.id}"] button`);
btn.textContent = likeButtonTextFor(comment);
})
}
function likeButtonTextFor(comment) {
return `${comment.likes} like${comment.likes === 1 ? '' : 's'} `
}
Run
cd 06_PATCH_and_DELETE_Requests/assets
json-server --watch db.json
const commentList = document.querySelector('#comments');
document.querySelector('#refreshList').addEventListener('click', refreshList);
function refreshList() {
commentList.innerHTML = "";
fetch('http://localhost:3000/comments')
.then(res => res.json())
.then(comments => {
comments.forEach(renderComment)
})
}
function renderComment(comment) {
const li = document.createElement('li');
li.dataset.commentId = comment.id;
li.textContent = `${comment.body} `;
const likeBtn = document.createElement('button');
likeBtn.textContent = likeButtonTextFor(comment);
li.append(likeBtn);
likeBtn.addEventListener('click', (e) => addLike(comment));
commentList.append(li);
}
function addLike(comment) {
fetch(`http://localhost:3000/comments/${comment.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({likes: comment.likes += 1})
})
.then(res => res.json())
.then(comment => {
const btn = document.querySelector(`#comments li[data-comment-id="${comment.id}"] button`);
btn.textContent = likeButtonTextFor(comment);
})
}
function likeButtonTextFor(comment) {
return `${comment.likes} like${comment.likes === 1 ? '' : 's'} `
}