Refactor reactions.js to make Sonar happy

This commit is contained in:
Jan-Lukas Else 2023-12-20 15:32:36 +01:00
parent c1ec720c09
commit b606fb7f81
1 changed files with 23 additions and 18 deletions

View File

@ -1,11 +1,12 @@
(() => { (async () => {
const reactions = document.querySelector('#reactions'); const reactions = document.querySelector('#reactions');
const path = reactions.dataset.path; const path = reactions.dataset.path;
const allowed = reactions.dataset.allowed.split(','); const allowed = reactions.dataset.allowed.split(',');
// Function to update reaction counts
const updateCounts = async () => { const updateCounts = async () => {
try { try {
const response = await fetch('/-/reactions?path=' + encodeURI(path)); const response = await fetch(`/-/reactions?path=${encodeURI(path)}`);
const json = await response.json(); const json = await response.json();
for (const reaction in json) { for (const reaction in json) {
@ -13,35 +14,39 @@
button.textContent = `${reaction} ${json[reaction]}`; button.textContent = `${reaction} ${json[reaction]}`;
} }
} catch (error) { } 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(); const data = new FormData();
data.append('path', path); data.append('path', path);
data.append('reaction', allowedReaction); data.append('reaction', allowedReaction);
return fetch('/-/reactions', { method: 'POST', body: data }) try {
.then(updateCounts) await fetch('/-/reactions', { method: 'POST', body: data });
.catch((error) => { await updateCounts();
console.error(error); } catch (error) {
}); console.error('Error handling reaction click:', error);
}
}; };
// Create buttons for each allowed reaction
allowed.forEach((allowedReaction) => { allowed.forEach((allowedReaction) => {
const button = document.createElement('button'); const button = document.createElement('button');
button.dataset.reaction = allowedReaction; button.dataset.reaction = allowedReaction;
button.addEventListener('click', () => handleReactionClick(allowedReaction)); button.addEventListener('click', () => {
handleReactionClick(allowedReaction).then(() => {});
});
button.textContent = allowedReaction; button.textContent = allowedReaction;
reactions.appendChild(button); reactions.appendChild(button);
}); });
(async () => { // Initial update of counts
try { try {
await updateCounts(); await updateCounts();
} catch (error) { } catch (error) {
console.error(error); console.error('Error during initial update:', error);
} }
})(); })();
})();