Issue
I'm using DOM to create an element for me that shows the amount of likes a specific comment has received. When someone likes the button that data gets pushed to the API. However, in order to see the number of likes increase I have to manually reload the page.
Is there a way to automatically refresh that specific DOM element so that when a user clicks the like button the amount of likes will automatically increase (so refresh) without having to manually reload the website?
// shows the amount of likes
const likeCounter = document.createElement("p");
likeCounter.classList.add("comments__container-content-like-counter");
functionsDiv.appendChild(likeCounter);
likeCounter.innerText = commentData.likes;
// likes a comment and adds it to the api
commentLike.addEventListener("click", () => {
const addLike = commentData.id;
axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
console.log("Like has been added!");
});
});
Solution
Here you go:
// shows the amount of likes
const likeCounter = document.createElement("p");
likeCounter.classList.add("comments__container-content-like-counter");
functionsDiv.appendChild(likeCounter);
likeCounter.innerText = commentData.likes;
// likes a comment and adds it to the api
commentLike.addEventListener("click", () => {
const addLike = commentData.id;
axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
console.log("Like has been added!");
likeCounter.textContent = Number(likeCounter.textContent)+1
});
});
Just add the line
likeCounter.textContent = Number(likeCounter.textContent)+1
to the promise chain.
Answered By - connexo Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.