From 9f7d009abbfaec78e30880b68bfc84c8a9598b83 Mon Sep 17 00:00:00 2001 From: JP Hastings-Spital Date: Sun, 7 Apr 2024 11:28:45 +0100 Subject: [PATCH] Update claps on page load --- assets/js/main.js | 21 ++++++++++++++++++++- layouts/partials/claps.html | 2 +- layouts/shortcodes/topclaps.html | 2 +- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/assets/js/main.js b/assets/js/main.js index 03fbdf20..57e6416b 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -73,12 +73,31 @@ const forEveryClapButton = (fn, sameAction = '') => { } document.addEventListener("DOMContentLoaded", () => { + let toCheck = [] forEveryClapButton((btn) => { - const lastClappedTo = localStorage.getItem(clapKey(btn.parentElement.action)); + const action = btn.parentElement.action + const lastClappedTo = localStorage.getItem(clapKey(action)); + toCheck.push(action) if (lastClappedTo) { btn.parentElement.classList.add('clapped') setClapCount(btn, lastClappedTo) } btn.addEventListener("click", performClap) }) + + toCheck.forEach((action) => { + fetch(action, { method: 'GET', headers: new Headers({ 'Accept': 'application/json' }) }) + .then(res => { + if (res.status !== 200) { + throw new Error(`Got HTTP ${res.status} while trying to retrieve claps`) + } + return res.json() + }) + .then(data => { + forEveryClapButton((btn) => { + setClapCount(btn, data.claps); + }, action) + }) + .catch(console.error) + }) }) diff --git a/layouts/partials/claps.html b/layouts/partials/claps.html index daf912ec..ca85e1b1 100644 --- a/layouts/partials/claps.html +++ b/layouts/partials/claps.html @@ -4,7 +4,7 @@