I have a PUT request that i want to add one to the current "points" data i get from the database. However, if a user clicks the handleDismissButton quickly, it could add 2 or 3 times which is incorrect. Is the only option to disable the button after click? Or is there a best practice?
function Block() {
async function handleDismissButton() {
try {
const response = await fetch(`/api/user/${userId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: {
showAward: true,
points: points += 1
}
});
const users = await response.json();
return users;
} catch (err) {
return null;
}
}
return (
<button
role="button"
onClick={() => handleDismissButton()}
>
Click here
</button>
);
}
2
Answers
The idempotent of PUT requests has little to do with this, because it indeed assumes that you actually send the same request multiple times.
Given all this logic is happening in the frontend, you can indeed just prevent the request from happening twice by disabling the button. You can also set some variable like ‘updateInProgress’ that you set to true when the initiate the request. You can then can check this variable when you’re about to do the request again (preventing this).
One approach to address the issue of multiple button clicks leading to incorrect point increments is to disable the button temporarily after the first click. Disabling the button prevents users from clicking it again until the server response is received and the UI is updated accordingly.