Search code examples
vue.jsvuexvuex-modules

Getting an object instead a number from rootState vuex


I'm trying to get activeTables from tables state.

const state = {
    activeTable: 0,
    tables: [{id:1},{id:2}],
}

When I do rootState.tables.activeTable from another module I get Object but I would like the value.

I tried to go deeper in tree structure in console.log but I can't get the value

const actions = {
    async addCommand ({commit, rootState},articles) {
        console.log(rootState.tables.activeTable) // getting an object instead a number
        commit('ADD_COMMAND', {table_id:rootState.tables.activeTable,list:articles})
        await api.insert(articles)
    },
}

// store/index.js

import Vuex from 'vuex'
import Vue from 'vue'
import products from './modules/products.js'
import tables from './modules/tables.js'
import command from './modules/command.js'

Vue.use(Vuex)

export default new Vuex.Store({
    modules : {
        products,
        tables,
        command
    },
})


store/modules/tables.js


const state = {
    activeTable: 0,
    tables: [{id:1},{id:2}],
}

const getters = {
    tables: state => state.tables,
    activeTable: state => state.activeTable,
    
}

const actions = {
    setActiveTableId (id) {
        this.commit('SET_ACTIVE_TABLE', id)
    }
}

const mutations = {
    SET_TABLES:(state, tables) => {
        state.tables = tables;
    },
    SET_ACTIVE_TABLE:(state, id) => {
        state.activeTable = id
    }
}

export default {
    state: state,
    mutations: mutations,
    getters: getters,
    actions: actions,
    strict: true,
}

store/modules/command.js

const state = {
    listCommand: []
}

const getters = {
    listCommand: state => state.listCommand
}

const actions = {
    async addCommand ({commit, rootState},articles) {
        console.log(rootState.tables)
        api.setUrl(api.url+'&table=command')
        commit('ADD_COMMAND', {table_id:rootState.tables.activeTable,list:articles})
        await api.insert(articles)
    },
    async addOrderLine({commit}, product){
        api.setUrl(api.url+'&table=orderline')
        await api.insert(product)
    }
}

const mutations = {
    ADD_COMMAND: (state, articles) => {
        state.listCommand.push(articles)
    },
    SET_LISTCOMMAND:(state, articles) => {
        state.listCommand = {table_id:state.activeTable,list:articles};
    },
}

export default {
    state: () => state,
    mutations: mutations,
    getters: getters,
    actions: actions,
    strict: true,
}

Solution

  • My error is in the "store/modules/tables.js"

    I forgot to add {commit} argument..

    before
    
    const actions = {
        setActiveTableId (id) {
            this.commit('SET_ACTIVE_TABLE', id)
        }
    }
    after
    const actions = {
        setActiveTableId ({commit},id) {
            this.commit('SET_ACTIVE_TABLE', id)
        }
    }
    

    Thanks all