Ali Ahmadi
Ali Ahmadi

Reputation: 741

How can i intercept an on-click asynchronously

I have a component with a button which handles some stuff, i want to pass an interceptor to this component so i can call an API inside the interceptor and ask for permission, if permission is granted the code inside the component's button's onClick is executed and if not, well it is not
So right now i'm having trouble figuring out what to do, here is a sudo code showing what i want to do:

//Inside componentA which is using componentB
onClickInterceptor = () => {
    axios.post(//something)
        .then(response => {
            // do a few thing and finally you know if you should return true or not
        })
        .catch(error => {
            //you know you don't have permission
        })


    return //This is my problem, i don't know what to return, i don't want to return the axios post, i want something like a new promise ?        
}

//Inside componentB
onButtonClick = (event) => {
    if (this.props.onClickInterceptor) {
        this.setState({ disableButton: true })

        this.props.onClickInterceptor()
            .then(permissionState) => {
            if (permissionState) {
                this.runTheMainCode()
            }
            else {
                //dont do anything
            }

            this.setState({ disableButton: false })
        }
    }
    else    
        this.runTheMainCode()
}

this.runTheMainCode() {
    //...
}  

Right now i don't know what to return inside onClickInterceptor, i know i don't want to to return the axios, but how can i return a promise like that which only returns true or false ?
By the way, i want the button to be disabled until the interceptor is done

Upvotes: 1

Views: 86

Answers (1)

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

You need to return the axios promise and handle it at the componentB

//Inside componentA which is using componentB
onClickInterceptor = () => {
    return axios.post(//something)
        .then(response => {
            // you can return false or true here
            return true 
        })
        .catch(error => {
            throw error
        })      
}

//Inside componentB
onButtonClick = (event) => {
   this.props.onClickInterceptor.then(returnedBoolean=>{
   // here will come what you returned
      this.setState({ disableButton: returnedBoolean })
   }).catch(err=>{
   // the error hadnling ....
   this.setState({ error: true })
   })
}

Upvotes: 1

Related Questions