Skip to content

Commit

Permalink
Refactor reactions.js to make Sonar happy
Browse files Browse the repository at this point in the history
  • Loading branch information
jlelse committed Dec 20, 2023
1 parent c1ec720 commit b606fb7
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions templates/assets/js/reactions.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,52 @@
(() => {
(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) {
const button = document.querySelector(`#reactions button[data-reaction="${reaction}"]`);
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);
}
})();

0 comments on commit b606fb7

Please sign in to comment.