Learner
Learner

Reputation: 119

React — How to make a button (that prevents double clicking while handling HTTP requests)

**trying the following The button will first be disabled when the promise fires. It will remain disabled until the promise resolves, where it will then be enabled again. Please advise as I am stuck here and not sure whether its the right thing **

let [enabled] = useState(false);
const getTotal = event => {
        enabled = false;
        calTotal().then(validateResult => {
           // enabled = true;
        });
    }
    <Button 
    onClick={() => new Promise((resolve) => {
              resolve({
                      getTotal();
                     })
                 })}>Get Total</Button>

Upvotes: 0

Views: 1472

Answers (1)

mahi-man
mahi-man

Reputation: 4686

There are a few things to consider:

  1. You are not setting the state of enabled correctly - you need to use the function from the useState hook
  2. You don't need to wrap the onClick in a promise
  3. You are not binding the button disabled property to your enable variable
  4. Your initial state of enabled will need to be true in order to be able to click the button

See adjustments here:

let [enabled, setEnabled] = useState(true);
const getTotal = event => {
    setEnabled(false)
    calTotal().then(validateResult => {
       setEnabled(true)
    });
}
<Button disabled={!enabled} onClick={() => getTotal()}>Get Total</Button>

Upvotes: 1

Related Questions