Search code examples
vue.jsstorevuex

Get a value from an observer in a Vuex getter


I have namespace module with a getter method called allItems() to get an array of values from a normalized state.

...    
getters: {
    allItems(state, getters, { entities }) {
        return state.items.map(function (item){
            return {...entities.product[item]};
        });
    }
}

When I try to get other elements, it gives me the "you can't call some property from undefined element" error.

If I put console.log(entities) I can see the array of elements and when I put console.log(entities.products) I got an observer {__ob__: Observer} with the data inside but when I put console.log(entities.products[1]) for example, I got undefined. What should I do to solve this?


Solution

  • I solved this creating a method getter called getEntityById like this

    getters: {
        getEntityById: (state) => (entity, id) => {
            return state[entity][id];
        }
    }
    

    And calling it on a map function