skip to Main Content

I have a enable/disable button for user ability. I want to add a confirmation before it gets turned on/off.

js:

function(){
I want to write a confirmation code here….
api call(url, data, method)
}
if not confirmed…

return false..and dont toggle the button…

However, in my case (intially button on) its not sending the request if not confirmed but it will toggle the button (button Off). After I refresh, it sets to previous value.. (button on)

Please help me not to toggle the switch when request is not sent when not confirming and likewise

2

Answers


  1. Hi you can use the confirm dialogue present in JS
    the confirm(…) will return true or false based on user selecting Yes or No

    const isConfirmed = confirm('Toggle button?')  
    if(isConfirmed) {
      // ... run your function
    }
    
    
    
    Login or Signup to reply.
  2. You can use promise to solve your problem.

    Using promises ensures that the UI state is not updated until the confirmation is resolved and the API call is completed successfully.

    let confirmed = false;
    
    const confirmAction = () => {
      return new Promise((resolve, reject) => {
        const isConfirmed = window.confirm('Do you confirm it?');
        confirmed = isConfirmed;
        
        if(confirmed) {
          resolve();
        } else {
          reject(new Error('Confirmation rejected.'));
        }
      });
     };
     
     const makeApiCall = (url, data, method) => {
        //API call implementation here
        //...
        //Return a promise that is based on the API response
     }
     
     const toggleButtonState = () => {
      confirmAction()
        .then(() => makeApiCall(yourUrl, yourData, yourMethod))
        .then(() => toggleButton())
        .cateh((error) => console.error(error));
     };
     
     const toggleButton = () => {
      if(confirmed) {
        //Toggle the button here
        //...
      }
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search