Tobi
Tobi

Reputation: 43

How to set data from external callback in Vue?

I included some external SDK into my component:

mounted() {
    // Load external Script
    let externalScript = document.createElement('script')
    externalScript.setAttribute('src', 'https://x.klarnacdn.net/kp/lib/v1/api.js')
    document.head.appendChild(externalScript)
    ...

Later I am receiving a callback like this:

authorizeKlarna: function(){  
        Klarna.Payments.authorize({
        payment_method_category: "pay_later"
        }, function(res) {
        console.debug(res);
        if(res.approved == true){ 
            this.token = res.authorization_token
        }
        })
      },

However this.token will not be updated because I am out of scope. Is there any simple way how to access data of my vue component from this external callback?

Upvotes: 0

Views: 645

Answers (1)

Adam Orłowski
Adam Orłowski

Reputation: 4484

Try changing your function(res) to Arrow Function (res) =>

authorizeKlarna: function(){  
  Klarna.Payments.authorize(
  { payment_method_category: "pay_later" },
  (res) => {
    console.debug(res);
    if(res.approved == true){ 
      this.token = res.authorization_token
    }
  }
)
},

Upvotes: 1

Related Questions