Using Vuex actions with async/await for API calls is a common pattern in Vue.js applications. This allows you to manage asynchronous operations such as fetching data from an API in a clean and organized way. Here's a step-by-step guide on how to do it:
Set up your Vuex store: Make sure you have Vuex installed and set up in your Vue.js application. This typically involves creating a store directory, defining your state, mutations, actions, and getters.
Define your action: Inside your Vuex store module, define an action that will handle the API call. This action should be asynchronous and use async/await
for handling promises returned by API requests. Here's an example:
javascript// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// Your state variables
data: null,
loading: false,
error: null
},
mutations: {
// Your mutation definitions
setData(state, data) {
state.data = data
},
setLoading(state, value) {
state.loading = value
},
setError(state, error) {
state.error = error
}
},
actions: {
async fetchData({ commit }) {
commit('setLoading', true)
try {
const response = await axios.get('https://api.example.com/data')
commit('setData', response.data)
} catch (error) {
commit('setError', error.message)
}
commit('setLoading', false)
}
},
getters: {
// Your getter definitions
getData: state => state.data,
isLoading: state => state.loading,
getError: state => state.error
}
})
fetchData
action from any of your Vue components. This will initiate the API call and update the state accordingly. For example:javascript// MyComponent.vue
<template>
<div>
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<div v-else>{{ data }}</div>
<button @click="fetchData">Fetch Data</button>
</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'getData',
'isLoading',
'getError'
])
},
methods: {
...mapActions([
'fetchData'
])
}
}
</script>
In this example, mapActions
and mapGetters
from Vuex are used to map the actions and getters to the component's methods and computed properties respectively. When the "Fetch Data" button is clicked, the fetchData
action is dispatched, which triggers the API call and updates the state accordingly. The component reacts to changes in the state by displaying loading indicators, error messages, or fetched data.