[Vuejs]-Exported data is null when using it in another javascript vue js file

1👍

This happens because your API takes a while to respond, but JavaScript continues running the function in parallel. Your state is still ‘null’ while the call hasn’t returned, thus this.cart will be set to null, unless you tell JavaScript to wait until the call is finished.

Try making the getCart() method an asynchronous function:

methods:{
            async getCart(){
                await store.getCart();
                this.cart=store.state.cartData;
                console.log("cart data: "+this.cart);                
        },

If cart should always be the same as the data in your store, a better way to do this might be to use a computed property for cart. This returns the store.state directly and will help you keep a single source of truth for your data.

computed: {
  cart() {
    return store.state.cartData
  }
}

Leave a comment