Search code examples
vue.jsvuex

Vuex use keys to access object in state


I have code like this for a store in Vuex, if do it like the code below it works fine.

state: {
    APIData: {},
},
getters: {
    getFeed: state => {return state.APIData },
},
mutations: {
    SET_FEED_DATA(state, {folder_id, data}) {
        state.APIData = data
    }
},

However, if I try to use a key to set and get the value it return undefined in the getter. I want to do this because I have a for loop in my template calling an action multiple times but with different id's that I will use here for the key value.

state: {
    APIData: {},
},
getters: {
    getFeed: state => {return state.APIData["test"] },
},
mutations: {
    SET_FEED_DATA(state, {folder_id, data}) {
        state.APIData["test"] = data
    }
},

Edit

Looking in Vue debugger I find the following, so it seems the mutation is setting that data but the getter can access it.

enter image description here


Solution

  • Inside the mutation, try to set it like below:

    state.APIData = { ...state.APIData, test: data };
    

    The getter is for APIData and it will not recognize the change if you update an individual property directly. You need to reset the whole APIData object.

    To replace the test with a variable:

    state.APIData = { ...state.APIData, [VARIABLE_NAME]: data };
    

    For example, if you want to pass the key name as folder_id in your code:

    state.APIData = { ...state.APIData, [folder_id]: data };