How to use setTimeout on vuex action?
Asked Answered
D

1

7

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>
Dannica answered 11/4, 2020 at 7:58 Comment(0)
A
5

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.

Aikido answered 11/4, 2020 at 9:21 Comment(1)
It's working, thank you. I made a wrapper component, so each alert have separate timeoutDannica

© 2022 - 2024 — McMap. All rights reserved.