Add anonymous upvote functionality
This commit is contained in:
parent
d3ce523bfe
commit
87bc37e124
3 changed files with 91 additions and 0 deletions
37
static/upvote.js
Normal file
37
static/upvote.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
(async function () {
|
||||
// Define the slug
|
||||
const slug = location.pathname.replace(/^\/|\/$/g, "").replaceAll("/", "-");
|
||||
const API = "http://localhost:3000";
|
||||
|
||||
const btn = document.getElementById("upvote-btn");
|
||||
const count = document.getElementById("upvote-count");
|
||||
|
||||
// On load fetch curent vote count and whether the button should be clicked on or off
|
||||
const res = await fetch(`${API}/posts/${slug}/votes`, {
|
||||
credentials: "include",
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
count.textContent = data.vote_count;
|
||||
if (data.voted) btn.setAttribute("voted", true);
|
||||
|
||||
btn.addEventListener("click", async () => {
|
||||
const alreadyVoted = btn.hasAttribute("voted");
|
||||
|
||||
const method = alreadyVoted ? "DELETE" : "POST";
|
||||
const r = await fetch(`${API}/posts/${slug}/vote`, {
|
||||
method,
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (r.ok) {
|
||||
const updated = await fetch(`${API}/posts/${slug}/votes`, {
|
||||
credentials: "include",
|
||||
});
|
||||
const d = await updated.json();
|
||||
count.textContent = d.vote_count;
|
||||
if (d.voted) btn.setAttribute("voted", false);
|
||||
else btn.removeAttribute("voted");
|
||||
}
|
||||
});
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue