0

**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>
Learner
  • 99
  • 3
  • 14
  • 1
    Does this answer your question? [ReactJs: Prevent multiple times button press](https://stackoverflow.com/questions/35315872/reactjs-prevent-multiple-times-button-press) – Alexander Staroselsky Apr 27 '20 at 20:16

1 Answers1

1

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>
mahi-man
  • 4,326
  • 2
  • 25
  • 36