user10745267
user10745267

Reputation: 81

How to access Vue component data inside callback

Im trying to integrate Paymentez (a payments processor) into my site. I get "success" or "failure" responses after doing a test transaction but cant change data in the Vue component (want to show a modal/dialog).

data: function() {
   return {
      success: false,
      failure: false
   }
},
created() {
    this.paymentCheckout = new window._PAYMENTEZ.modal({
        client_app_code: "***********", // Client Credentials
        client_app_key: "***************", // Client Credentials
        locale: "es", // User's preferred language (es, en, pt). English will be used by default.
        env_mode: "stg", // `prod`, `stg`, `local` to change environment. Default is `stg`
        onOpen: function () {
          console.log("modal open");
        },
        onClose: function () {
          console.log("modal closed");
        },
        onResponse: function (response) {
          // The callback to invoke when the Checkout process is completed

          /*
        In Case of an error, this will be the response.
        response = {
          "error": {
            "type": "Server Error",
            "help": "Try Again Later",
            "description": "Sorry, there was a problem loading Checkout."
          }
        }

        When the User completes all the Flow in the Checkout, this will be the response.
        response = {
          "transaction":{
              "status": "success", // success or failure
              "id": "CB-81011", // transaction_id
              "status_detail": 3 // for the status detail please refer to: https://paymentez.github.io/api-doc/#status-details
          }
        }*/

          console.log(response);
          document.getElementById("response").innerHTML = JSON.stringify(
            response
          );
        },
      });
    /* what I want is something like:
       if(response.transaction.status == "success") {
            this.success = true
       }
       else if(response.transaction.status == "failure") {
            this.failure = true
       }
       else if (response.error) {
            // show error
       }
     */

I've added the Paymentez library via CDN and initialized it in a created() hook.

this.success and this.failure remain false.

Cant access this inside the callback

Upvotes: 1

Views: 470

Answers (1)

tao
tao

Reputation: 90277

To be able to access the outer this, your callbacks need to be arrow functions. Example:

// ...
  onResponse: response => {
    this.success = true; // <= works! (changes your component's reactive prop).
    console.log('console is your friend', this);
    console.log(response);
  }
//...

If they're normal functions they overwrite the outer this with their own scope (and that's what this points to inside them). Read more here.

Upvotes: 2

Related Questions