Reputation: 1959
Why when I call
getters.getEventById(id)
not work the same way when I call
state.events.find(event => event.id === id)
Take a look on both console.log on the beggining of fetchEvent action.
fetchEvent({ commit }, id) {
var event = getters.getEventById(id)
console.log(event)
console.log(state.events.find(event => event.id === id))
if (event) {
commit('SET_EVENT', event)
} else {
EventService.getEvent(id)
.then(response => {
commit('SET_EVENT', response.data)
})
.catch(error => {
console.log(error.response)
})
}
}
}
export const getters = {
getEventById: state => id => {
return state.events.find(event => event.id === id)
}
}
The result is:
Upvotes: 0
Views: 145
Reputation: 1828
There seem to be some code missing from your snippet: how does fetchEvent
have access to the state
and the getters
? Normally, Vuex actions receive the state
and the getters
via their first argument.
I took your code, put it in a simple Vuex boilerplate, refactored it a bit, and it's working as you would expect.
Vue.component('event', {
template: '<div></div>',
created() {
this.$store.dispatch('fetchEvent', 1);
},
});
const store = new Vuex.Store({
state: {
events: [{
id: 1
},
{
id: 2
},
{
id: 3
},
]
},
actions: {
fetchEvent({
commit,
state,
getters,
}, id) {
var event = getters.getEventById(id)
console.log('getter:', event)
console.log('local find:', state.events.find(event => event.id === id))
}
},
getters: {
getEventById: state => id => {
return state.events.find(event => event.id === id)
}
}
})
const app = new Vue({
store,
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<event></event>
</div>
Upvotes: 1