Search code examples
reactjscallbackthisbraintree

can't access 'this' function in React callback


I have a React component where by I need to change the state after a successful database call. The database call uses a callback function, which I can't change, however I can't find a way to access the redirect function in the same component, from within the call back function. I just get the error enableRedirect' of null

I've tried changing the callback function to an arrow function, but then it doesn't get called correctly. I've been reading other answers to similar problems, but can't make it apply to my situation

    ...
    componentDidUpdate = (prevProps, prevState) => {
    if (prevState.braintreeToken !== this.state.braintreeToken) {

      dropin.create(
        {
          authorization: this.state.braintreeToken,
          container: "#dropin-container",
        },
//callback function happens here
        (createErr, instance) => {
          button.addEventListener("click", function() {
            instance.requestPaymentMethod(function(
              requestPaymentMethodErr,
              payload
            ) {
              api
                .submitPayload(payload, plan, id)
                .then(res => {
                  //this is where I'm trying to call my enable redirect function
                  this.enableRedirect();
                })
                .catch(err => {
                  //error handling
                });
            });
          });
        }
      );
    }
  };

    // the function I'm trying to call
    enableRedirect = () => {
      this.setState({
        redirect: true
      });
    };
 ...

I need the enableRedirect Function to be called in the callback!


Solution

  • Instead of this

    button.addEventListener("click", function() {
    
    });
    

    Use

    button.addEventListener("click", () => {
    
    });
    

    Value of this is not the same for arrow function and normal function. For a normal function this will be the button you clicked.

    Refer this link.