After creating a Vue.js app with vuex as a central store and using axios for basic API calls, I implemented the following store action:
loadConstituencyByAreaCodeAndParliament({commit}, {parliament_id, area_code}) {
axios.get('/cc-api/area-code/' + parliament_id + '/' + area_code)
.then((response) => {
commit('SET_CONSTITUENCY', response.data);
})
.catch(function(error){
commit('SET_CONSTITUENCY', null);
}
)
}
In a single component file, I created a form for users to input an area code. This form triggers the above action to retrieve the constituency corresponding to the area code:
export default {
name: 'AreaCodeForm',
components: {
PostalCodeInput
},
props: ['parliament_id'],
data: () => ({
postalCode: ''
}),
methods: {
search_area_code(submitEvent) {
let area_code = submitEvent.target.elements.area_code.value;
let payload = {
parliament_id: this.parliament_id,
area_code
}
this.$store.dispatch('loadConstituencyByAreaCodeAndParliament', payload).
then(() => {
let constituency = this.$store.getters.getConstituency();
// do some things with the data received from the API
// but everything depending on constituency does not work the first time.
// Data received from the API is here available only from the second time on
// wehen this code run.
})
}
}
}
Despite expecting the $store.dispatch
method to return a promise and populate the constituency
variable with fetched data, it remains empty initially. The issue resolves itself upon re-entering the area code. It appears that even with the use of promise.then
, the data is not immediately stored in the store. Subsequent attempts yield the expected results.