Search code examples
vue.jsvuejs2vue-componentvuexvue-router

How to fill items of the state in vue


I have a cart with id and when I make the call with cart_guid (carts/70290ee4-258b-11cb-9ca4-42ca64dfa778) the json:

{
    "data": {
        "type": "carts",
        "id": "70290ee4-258b-11cb-9ca4-42ca64dfa778",
        "attributes": {
            "cart_guid": "70290ee4-258b-11cb-9ca4-42ca64dfa778",
            "total_price_excl_vat": 70,
            "total_vat": 66.5,
            "total_price_incl_vat": 136.5,
            "items": [
                {
                    "id": 300,
                    "cart_id": 663,
                    "product_id": "2021-05-07.1.1",
                    "product_name": "Product",
                    "product_short_description": "short description",
                    "product_image": "img",
                    "variation_id": 1,
                    "variation_name": "child",
                    "price_excl_vat": 10,
                    "vat_percentage": 0.95,
                    "amount": 7,
                    "created_at": "2021-10-26T11:29:31.000000Z",
                    "updated_at": "2021-10-26T11:30:02.000000Z"
                }
            ],
            "createdAt": "2021-10-26T11:29:09.000000Z",
            "updatedAt": "2021-10-26T11:30:02.000000Z"
        }
    }
}

So when I refresh the page items are being empty again and I am really confused about how to fill them. So my state:

export default {
    cart: {
        "attributes": {
            "items": [],
        }
    }
}

mutation:

export const ADD_TO_CART = (state, {cart}) => {
    state.cart = cart;
}

and action:

export const addProductToCart = ({commit}, {cart}) => {
    commit('ADD_TO_CART', {cart});
}

By the way, I can fill the items when I click the add to cart button and logic is here:

addToCart: function () {
            this.amount = this.itemsCount !== "" ? this.itemsCount : 1;
            if(this.variationId != null) {
                this.warningMessage = false;
                cartHelper.addToCart(this.product.id, this.variationId, parseInt(this.amount), (response) => {
                    this.$store.dispatch('addProductToCart', {
                        cart: response.data,
                    })
                });
            } else {
                this.warningMessage = true;
            }
        },

I am really confused about how to achieve it and I know a lot of code but hope you can help me. Lastly, here I tried to check if there it cookieValue (which is cart_guis) call the cart:

checkCart: function(callback = undefined) {
        if(this.cookieValue != null) {
            this.getCart((response) => {
                if (callback) { callback(response); }

                console.log("cookie var")
            });
        } 
    },

And in my index.vue I am trying to mount this:

mounted() {
        cartHelper.checkCart((response) => {
            if(response.data.attributes.item == null) {
                this.$store.dispatch('addProductToCart', {
                    cart: response.data,
                })
            }
        });
    },

enter image description here


Solution

  • I am using vuex-persistedstate and I think this would be a good choice, you could find it here. As it's said vuex-persistedstate will

    Persist and rehydrate your Vuex state between page reloads.

    and your data will be on the local storage of your browser, then you could just use it simply. I will provide the example below.

    mutation :

    export const addToCart = (state, response) => {
      const findingItem = state.cart.findIndex(item => item.id === response.id);
    
      if (findingItem === -1) {
        state.cart.push(response);
      }
    };
    

    ( For avoiding repeated items.)

    index.js : (store configuration)

    import Vue from 'vue';
    import Vuex from 'vuex';
    import createPersistedState from 'vuex-persistedstate';
    
    import module1 from './module1';
    
    Vue.use(Vuex);
    
    const Store = new Vuex.Store({
      modules: {
        module1,
      },
    
      plugins: [createPersistedState()],
     
    });
    
    export default Store;
    

    addToCart function :

      this.$store.commit('module1/addToBag', item, {
          module: 'module1',
        });
    

    showing the bag :

    created() {
        this.cart = this.$store.state.module1.cart;
      },
    

    ps : I used a modular way of store.