[Vuejs]-Not able to access data variable in script after populating it with json from an ajax call

2πŸ‘

βœ…

In your data object add a property called itemPromise

   GetItemsList() { 
          this.itemPromise = CommonFunctions.GetItemPriceListByID("ItemList").done(); 
     }

in the mounted hook add this :

    this.itemPromise.then((res)=>{this.itemPriceList=res})

UPDATE

in the created hook we had created a Promise object by calling the GetItemsList() and assigning that promise to itemPromise property, in the mounted hook we use the itemPromise.then(res=>{...}) to assign the result to our itemPriceList property

3πŸ‘

this.GetItemsList() is being called in created, but is an asynchronous method, so Vue continues to call the rest of the lifecycle hooks.

Whats happening is β€œmounted” is being called before the Ajax call returns, so the list is empty.

Try this:

GetItemsList() {
            this.itemPriceList = CommonFunctions.GetItemPriceListByID("ItemList")
                .done(data => {
                    this.itemPriceList = data;
                    console.log("Completed")

                    console.log(this.itemPriceList)
                    // Additional logic here

                }); //result;
        }

Any logic dependant on itemPriceList being set should be added inside the arrow function, or as additional methods that are called inside the arrow function.

πŸ‘€HMilbradt

Leave a comment