1

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
};
1
  • 1
    Observer in console observes the changes and is refreshed when you add an item. So, everything looks fine Commented Feb 22, 2021 at 15:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.