skip to Main Content

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


  1. 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).

    Login or Signup to reply.
  2. 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.

    import { useState } from 'react';
    
    function Block() {
      const [buttonDisabled, setButtonDisabled] = useState(false);
    
      async function handleDismissButton() {
        if (buttonDisabled) {
          return;
        }
    
        try {
          setButtonDisabled(true); // Disable the button
    
          const response = await fetch(`/api/user/${userId}`, {
            method: "PUT",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              showAward: true,
              points: points + 1
            })
          });
    
          // Handle the response and update the UI if needed
    
        } catch (err) {
          // Handle errors
        } finally {
          setButtonDisabled(false); // Re-enable the button
        }
      } 
    
      return (
        <button
          role="button"
          onClick={() => handleDismissButton()}
          disabled={buttonDisabled} // Disable the button based on the state
        >
          Click here
        </button>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search