programing

Vuex - 여러 디스패치 후 기능 실행

bestcode 2022. 8. 9. 21:44
반응형

Vuex - 여러 디스패치 후 기능 실행

애플리케이션을 만들고 있어 데이터를 로드해야 하는데 사용자가 고장난 데이터를 보지 못하도록 로드 컴포넌트를 삽입합니다.

현재 로드에 set Timeout을 넣었지만 API 응답에 1초 이상 걸릴 수 있습니다.그래서 저는 모든 디스패치가 완료되어야만 로딩 상태를 업데이트 하고 싶습니다.

MainComponent.vue

beforeCreate() {
    this.$store.dispatch('responsibles/fetchData')
    this.$store.dispatch('events/fetchData')
    this.$store.dispatch('wallets/fetchData')

    // Need to run this setTimeout after all the above dispatches become completed...
    setTimeout(() => {
        this.loading = false
    }, 1000)
}

store/modules/responsibles.js

const state = {
    responsibles: []
}

const actions = {
    fetchData({dispatch}) {
        function getresponsibles() {
            return http.get('responsibles')
        }

        axios.all([
            getresponsibles()
        ]).then(axios.spread(function (responsibles) {
            dispatch('setResponsibles', responsibles.data.data)
        })).catch(error => console.error(error))
    },
    setResponsibles({commit}, responsibles) {
        commit('SET_RESPONSIBLES', responsibles)
    }
}

const mutations = {
    SET_RESPONSIBLES(state, responsibles) {
        state.responsibles = responsibles
    }
}

store/modules/events.js

const state = {
    events: []
}

const actions = {
    fetchData({dispatch}) {
        function getEvents() {
            return http.get('events')
        }

        axios.all([
            getEvents()
        ]).then(axios.spread(function (events) {
            dispatch('setEvents', events.data.data)
        })).catch(error => console.error(error))
    },
    setEvents({commit}, events) {
        commit('SET_EVENTS', events)
    }
}

const mutations = {
    SET_EVENTS(state, events) {
        state.events = events
    }
}

store/modules/wallets.js

const state = {
    wallets: []
}

const actions = {
    fetchData({dispatch}) {
        function getWallets() {
            return http.get('wallets')
        }

        axios.all([
            getWallets()
        ]).then(axios.spread(function (wallets) {
            dispatch('setWallets', wallets.data.data)
        })).catch(error => console.error(error))
    },
    setWallets({commit}, wallets) {
        commit('SET_WALLETS', wallets)
    }
}

const mutations = {
    SET_WALLETS(state, wallets) {
        state.wallets = wallets
    }
}
  1. 행동하다returnPromiseAxios에 의해 작성되었습니다.

    return axios.all(...
    

    https://vuex.vuejs.org/guide/actions.html#composing-actions 를 참조해 주세요.

  2. 디스패치 콜을 정리하고 모든 콜이 완료될 때까지 기다립니다.

    Promise.all([
      this.$store.dispatch('responsibles/fetchData'),
      this.$store.dispatch('events/fetchData'),
      this.$store.dispatch('wallets/fetchData')
    ]).finally(() => {
      // using "finally" so even if there are errors, it stops "loading"
      this.loading = false
    })
    

언급URL : https://stackoverflow.com/questions/54759153/vuex-run-function-after-multiple-dispatches

반응형