0

I'm using a payment api and there is a callback method from the api that will denote about the status of the transaction.

  async makePayment() {
            this.$launchFlutterwave({
                tx_ref: Date.now(),
                amount: this.amount,
                currency: "KES",
                customer: {
                    email: "user@gmail.com",
                    phonenumber: this.user.phone_number,
                    name: this.user.name,
                    plot_unique_id: this.plot_unique_id
                },
                callback: function(data) {
                    
                    console.log(data);
                    this.registerPayment(data);
                },
                customizations: {
                    title: "",
                    description: ",
                    logo: "https://assets.piedpiper.com/logo.png"
                }
            });
        },

 async registerPayment(data) {
            console.log("hit");
            await axios.post("/api/flutterwave/register/payment", data);
        }

Inside that callback, I want to register a method

  callback: function(data) {
        console.log(data);
        this.registerPayment(data);
     },

and then that method will post the received back data and other user specific data to the back-end

 async registerPayment(data) {
       console.log("hit");
       await axios.post("/api/flutterwave/register/payment", data);
  }

But when calling the method inside the callback I'm receiving the error Uncaught TypeError: this.registerPayment is not a function.

user3714932
  • 1,253
  • 2
  • 16
  • 29

1 Answers1

3

That's because the context inside the callback is different:

callback: function(data) {
  console.log(this); // you will see registerPayment doesnt exist here
  this.registerPayment(data);
},

Why not use the registerPayment directly? You can do so with:

callback: this.registerPayment

If you still want to call registerPayment from within the callback you can use arrow functions to access the outside context:

callback: (data) => {
  this.registerPayment(data);
}
Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61