Hello there. I'm currently having an issue where my page do not work after refresh. It is clear that in Vuex inspector the event: {...}
still has content. I have also tried asyncData()
instead of fetch()
, am I missing something here?
After refresh, it will says event is undefined
.
According to official tutorials, I also like to know if axios in store actions is good practice or not. Thank you very much.
events/_id.vue
<template>
<div>{{ event.attributes.name }}</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
validate ({ params }) {
return !isNaN(+params.id)
},
fetch ({ store, params }) {
if (store.state.events.event.id !== params.id) {
store.dispatch('events/getEvent', {
id: params.id
})
}
return store.state.events.event
},
computed: {
...mapGetters({
event: 'events/event',
error: 'events/error'
})
},
methods: {
...mapActions({
getEvent: 'events/getEvent'
})
}
}
</script>
store/events.js
// import { getUserFromLocalStorage } from '~/utils/auth'
export const state = () => ({
event: {},
events: [],
error: ''
})
export const getters = {
event: state => state.event,
events: state => state.events,
error: state => state.error
}
export const actions = {
async getEvent ({ commit, dispatch }, { id }) {
try {
await this.$axios.$get(`events/${id}`)
.then((res) => {
console.log(res.data)
commit('SET_EVENT', res.data)
dispatch('clearError')
})
} catch (err) {
dispatch('setError', err.response.data.error)
}
},
async getEvents ({ commit, dispatch }) {
try {
await this.$axios.$get('events')
.then((res) => {
commit('SET_EVENTS', res.data)
dispatch('clearError')
})
} catch (err) {
dispatch('setError', err.response.data.error)
}
},
setError ({ commit }, error) {
commit('SET_ERROR', error)
setTimeout(() => {
commit('CLEAR_ERROR')
}, 10000)
},
clearError ({ commit }) {
commit('CLEAR_ERROR')
}
}
export const mutations = {
SET_EVENT (state, payload) {
state.event = payload
},
SET_EVENTS (state, payload) {
state.events = payload
},
SET_ERROR (state, payload) {
state.error = payload
},
CLEAR_ERROR (state) {
state.error = null
}
}
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1395">#c1395</a>)</em></sub></div>