Search code examples
vue.jsvuex

Length of the state of vuex doesn't come out


There is a state in the vuex.

I defined 'images' as an array and when I print by console.log(state.images), the result came out like below.

[__ob__: Observer]
0: {…}
1: {…}
2: {…}
3: {…}
4: {…}
length: 5
__ob__: Observer {value: Array(5), dep: Dep, vmCount: 0}
__proto__: Array

After that, when I use console.log(state.images[0]) or console.log(state.images.length) doesn't work. Could you recommend some solution? Thank you so much for reading this.

EDIT) I write more code in detail.

const state = {
    images:[]
};

const mutations = {
    pushPresentImage(state, yo) {
        state.images.push(yo);
},

const actions = {
    imageLoad() {

    },

    imageLength({commit}, image){
        axios.post('/', ...)
           .then(result =>{ 
                commit('pushPresentImage', result.data.image)
            })
           .then(() => {
                console.log(state.images) // it works well like above.
                console.log(state.images[0]) // it says undefined.. 
            })
},

Solution

  • Seems like you are reading the state.images[0] array when the state is not fully saved by vuex. But I tried with the same code you used and it worked for me. Try restructuring your state so it does not stand alone:

    
    import Vue from "vue";
    import Vuex from "vuex";
    import axios from "axios";
    
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      state: {
        todos: []
      },
      mutations: {
        pushPresentImage(state, yo) {
          state.todos.push(yo);
        }
      },
      actions: {
        imageLoad() {},
        imageLength({ commit, rootState }, image) {
          axios
            .get("https://jsonplaceholder.typicode.com/todos/1")
            .then(result => {
              commit("pushPresentImage", result.data);
            })
            .then(() => {
              console.log(rootState.todos); // it works well like above.
              console.log(rootState.todos[0]); // it does not say undefined..
            });
        }
      }
    });
    
    export default store;
    

    Here is the sample code on codesandbox