Currently, I am diving into vuex and facing an issue. During the created() lifecycle hook, my goal is to fetch data from an API. Once this action is complete, I need to call a getter from the component and assign the retrieved cards to the component's cards array. Inside the created() method, I have added a comment for better understanding of my requirements. Is there a way to implement a "promise" type of behavior on dispatch? This will allow me to execute something after the asynchronous operation is finished. Thank you in advance for any help provided. Below is a code snippet along with a screenshot.
Component:
<template>
<div class="container" :class="{'is-loading': isLoading}">
<h1>All Cards</h1>
<hr>
<section class="columns">
<app-card :card="card" v-for="card in cards" key="asdasd" />
</section>
</div>
</template>
<script>
import axios from 'axios'
import AppCard from './AppCard'
export default {
name: 'AppCards',
components: {
AppCard
},
data () {
return {
isLoading: true,
endpoint: `/cards.json`,
cards: []
}
},
created() {
this.$store.dispatch('fetchAllCards', this.endpoint)
// then(() => {
// this.cards = this.$store.getters.allCards (I want to get cards once action / mutation did its job and assign to this component's cards )
// })
}
}
</script>
Vuex:
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import axios from 'axios'
Vue.use(Vuex)
const state = {
cards: null
}
const mutations = {
storeCards(state, fetchedCards) {
state.cards = fetchedCards
}
}
const actions = {
fetchAllCards({commit, state}, payload) {
axios.get(payload)
.then(response => {
const data = response.data
const cards = []
for(let key in data) {
if(data[key] !== null) {
const card = data[key]
card.id = key
cards.push(card)
}
}
commit('storeCards', cards)
})
.catch(e => {
console.log(e)
})
}
}
const getters = {
allCards(state) {
return state.cards
}
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})