Search code examples
javascriptvue.jsbrowserconsolevuex

Vuex state returning incorrect value


I'm having an issue where I am getting an unexpected value from the store.

I have a component with one method:

methods: {
    setProduct(product) {
        this.$store.commit('basket/empty');
    
        console.log(this.$store.state.basket.items);
  
        this.$store.commit("basket/addToBasket", {
            id: product.id
        });
    },
},

It simply empties the basket and adds a new product, thus one product can exist in the basket at any one time.

My issue is that the console log is returning a product.

enter image description here

Rather than an empty array. If I remove

this.$store.commit("basket/addToBasket", {
    id: product.id
});

it is returns

enter image description here

Please can someone tell me why the console.log is returning items, when the commit hasn't taken place yet?

Basket.js

const state = {
    items: []
};

const getters = {};
const actions = {};

const mutations = {
    empty (state) {
        state.items = [];
    },
    addToBasket (state, product) {
        state.items.push(product);
    },
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};

Solution

  • The developer console is able to update the data when logging a reference variable, like an Array or Object.

    When you click to expand in the console, it shows you the variable as it is at the time you click the console, not at the time it was logged. That means it does not necessarily reflect the value of the items variable at the time it was logged.

    In this case, the items array is empty when the log happens, but by the time you click to expand the properties, the array contains the new id.

    Here is a demo that illustrates this a little more.