0

i am developing a shopify theme, currently i am working on shopping cart page, i have CartForm.js file where i am importing data from cartData.js file. This is CartForm.js...

import { store } from "./../shared/cartData.js";
if (document.querySelector('.cart-form')) {


    let productForm = new Vue({
        el:".cart-form",
        delimiters: ['${', '}'],
        data(){
            return{
                cart:null,
            }
        },

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

and this is cartData.js file

export const  store = {

    state: {
        cartData:null
    },
    getCart(){   
        alert("store get cart called!...")     

        axios.get('/cart.js')
                .then( response => {                    
                     this.state.cartData=response.data;                     
                    console.log("Responsed data="+this.state.cartData);                    
                })
                .catch( error => {
                    new Noty({
                        type: 'error',
                        layout: 'topRight',
                        text: 'There was an error !!'
                    }).show();
                });
    }

}

As you can see i am explicitly calling store.getCart(); in CartForm's getCart() method, and when "Responsed data" gets printed it shows that this.state.cartData filled with data, but when i am using it like this: this.cart=store.state.cartData; this.cart is null, why is null? Any help is appreciated

1 Answer 1

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you now i have understand what's going on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.