Search code examples
vue.jsvuejs2vuexsettimeoutvuex-modules

How to use setTimeout on vuex action?


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>

Solution

  • Add it and remove it from the media actions:

    addMovieToFavourites({ commit, dispatch }, movie) {
      commit('ADD_FAVOURITE', movie)
      const alert = {
        type: 'success',
        message: 'Added to favourites!'
      }
    
      // Add alert
      dispatch('alert/setAlert', alert, { root: true })
    
      // Remove alert
      setTimeout(() => {
        dispatch('alert/removeAlert', { root: true })
      }, 3000)
    }
    

    If all alerts work this way, you could automatically trigger the removal from every alert by queueing it in the setAlert action:

    const actions = {
      setAlert({ commit }, alert) {
        commit('SET_ALERT', alert);
        setTimeout(() => {
          commit('REMOVE_ALERT');
        }, 3000);
      },
      ...
    }
    

    Then you wouldn't need the removeAlert action.

    You may also need some alert management or clearTimeout to handle multiple alerts within 3 seconds. As it's written, a previous alert's removal could mean that a later alert isn't shown for a full 3 seconds.