I am trying to set a variable declared at the beginning of the class (a boolean) to true once a callback is called, but I keep getting a TypeScript erorr.
Here is the error:
TypeError: Cannot set property 'nonReceived' of undefined
Here is my code:
finalizeToken(){
braintree.setup(JSON.parse(this.finalToken), 'dropin', {
container: 'dropin-container',
defaultFirst: true,
form: 'checkout-form',
onPaymentMethodReceived: function (obj) {
this.nonReceived = true;
localStorage.setItem('nonce', obj.nonce);
}
});
}
The brintree-setup connect to Braintree Payments, and awaits user payment info. Once they submit the form, I need the variable "this.nonReceived" to be set to true.
Just change the function call to const result = await Service. doCallAuth("test", "test") , Promises handle async/await pattern, and wrap the await call by try/catch pattern to catch errors.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.
If you use ES5 syntax you could use function(){}.bind(this)
to bind the callback with the context but with Typescript you can use ES6 syntax and use arrow function (parameters) => {function_body}
which bind current context implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With