From b606fb7f8118d591e16ee6e8792a270b76d11b4d Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Wed, 20 Dec 2023 15:32:36 +0100 Subject: [PATCH] Refactor reactions.js to make Sonar happy --- templates/assets/js/reactions.js | 41 ++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/templates/assets/js/reactions.js b/templates/assets/js/reactions.js index 9963fb8..877db30 100644 --- a/templates/assets/js/reactions.js +++ b/templates/assets/js/reactions.js @@ -1,11 +1,12 @@ -(() => { +(async () => { const reactions = document.querySelector('#reactions'); const path = reactions.dataset.path; const allowed = reactions.dataset.allowed.split(','); + // Function to update reaction counts const updateCounts = async () => { try { - const response = await fetch('/-/reactions?path=' + encodeURI(path)); + const response = await fetch(`/-/reactions?path=${encodeURI(path)}`); const json = await response.json(); for (const reaction in json) { @@ -13,35 +14,39 @@ button.textContent = `${reaction} ${json[reaction]}`; } } catch (error) { - console.error(error); + console.error('Error updating counts:', error); } }; - const handleReactionClick = (allowedReaction) => { + // Function to handle reaction click + const handleReactionClick = async (allowedReaction) => { const data = new FormData(); data.append('path', path); data.append('reaction', allowedReaction); - return fetch('/-/reactions', { method: 'POST', body: data }) - .then(updateCounts) - .catch((error) => { - console.error(error); - }); + try { + await fetch('/-/reactions', { method: 'POST', body: data }); + await updateCounts(); + } catch (error) { + console.error('Error handling reaction click:', error); + } }; + // Create buttons for each allowed reaction allowed.forEach((allowedReaction) => { const button = document.createElement('button'); button.dataset.reaction = allowedReaction; - button.addEventListener('click', () => handleReactionClick(allowedReaction)); + button.addEventListener('click', () => { + handleReactionClick(allowedReaction).then(() => {}); + }); button.textContent = allowedReaction; reactions.appendChild(button); }); - (async () => { - try { - await updateCounts(); - } catch (error) { - console.error(error); - } - })(); -})(); + // Initial update of counts + try { + await updateCounts(); + } catch (error) { + console.error('Error during initial update:', error); + } +})(); \ No newline at end of file