I would like to empty the alert state, so that the alert is not displayed, I don't really know how to trigger removeAlert action x seconds after addMovieToFavourites or removeMovieToFavourites executed, code below, thanks.
alert.js
const state = {
alert: null
}
const mutations = {
SET_ALERT(state, alert) {
state.alert = alert
},
REMOVE_ALERT(state) {
state.alert = null
}
}
const actions = {
setAlert({ commit }, alert) {
commit('SET_ALERT', alert)
},
removeAlert({ commit }) {
commit('REMOVE_ALERT')
}
}
media.js adding/ removing triggers the alert message
const actions = {
addMovieToFavourites({ commit, dispatch }, movie) {
commit('ADD_FAVOURITE', movie)
const alert = {
type: 'success',
message: 'Added to favourites!'
}
dispatch('alert/setAlert', alert, { root: true })
},
removeMovieFromFavourites({ commit, dispatch }, movie) {
commit('REMOVE_FAVOURITE', movie)
const alert = {
type: 'success',
message: 'Removed from favourites!'
}
dispatch('alert/setAlert', alert, { root: true })
},
}
alert.vue
<script>
import { mapActions, mapState } from 'vuex'
export default {
name: 'Alert',
data() {
return {
timeout: null
}
},
mounted() {
this.timeout = setTimeout(() => this.removeAlert(), 3000)
},
beforeDestroy() {
clearTimeout(this.timeout)
},
computed: {
alertTypeClass() {
return `alert-${this.alert.type}`
},
...mapState('alert', ['alert'])
},
methods: mapActions('alert', ['removeAlert'])
}
</script>