[Vuejs]-JS: 'this' context keeps showing as undefined when within promise chains

1👍

It looks like you were close.

TLDR;
At least when using Typescript or newer EcmaScript (JS) versions, using a lambda function (=>) will bind this to the correct object, hence Saurabh Agrawal’s comment.

When using an old variant of JS/EcmaScript, you have to get a reference to the this you want to pass into your chained methods, and then use that instead of this. If I recall, this is what Typescript or other transpilers use when targeting an older version, as well.

Using your code (untested), this would like like:

updateQuantity: function(e,item) {
            if (e === null || e === "") {
                return
            }
            let originalQuantity = item.original_quantity;
            let updatedQuantity  = parseFloat(e)

            // ADDED COMMENT -- looks like you already had a reference, just weren't using it
            var foo = this;

            // can access other functions here, ex: this.updateName();

            axios.post('/api/inventory/' + item.inventory_id + '/update-quantity', {
                original_quantity: item.original_quantity,
                quantity: updatedQuantity
            })
            .then(response => {
                if (response.data && response.data.status == "success") {
                    // EDIT -- use your variable reference to `this`
                    foo.showFlashMsg(response.data.message, true)
                    debugger
                } else if (response.data && response.data.status == "error") {
                    debugger
                }
            })
            .catch(err => {
                console.log(err);
            });
        },

Leave a comment