Currently, I am experimenting with Vuejs and Vuex. However, I am facing an issue when trying to update the view (vuejs) after making an AJAX call. Strangely, the view does not update when using arrays, objects, or booleans. Surprisingly, if I update a string via the store commit, it is properly reflected in the view. In the Vue developer tool, I can see that the Vuex / store is updating correctly. Interestingly, as soon as I make a change to any part of example.vue, hot reloading kicks in and the data is displayed.
I believe I must be missing something small but crucial, as I cannot seem to figure out what is required to trigger the update.
For this setup, I am utilizing the vue-cli tool and have included Axios and Vuex through npm.
This is the code I am working on:
store.jsimport Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export const StoreExample = new Vuex.Store({
state: {
customers: [],
isLoading: false,
},
getters: {
getCustomers: state => state.customers,
isLoading: state => state.isLoading,
},
mutations: {
setCustomers(state, payload) {
state.customers.push(payload)
},
setLoading(state, payload) {
state.isLoading = payload
}
},
actions: {
fetchCustomers({state, commit}) {
commit('setLoading', true)
axios.get('https://api.myjson.com/bins/rkyih')
.then(response => {
commit('setCustomers', response.data)
commit('setLoading', false)
})
.catch(e => {
console.error(e)
commit('setLoading', false)
})
}
},
strict: process.env.NODE_ENV !== 'production'
})
main.js
import Vue from 'vue'
import Vuex from 'vuex'
import { StoreExample } from './store/store.js'
import App from './App'
Vue.use(Vuex)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store: StoreExample,
components: { App },
template: '<App/>'
})
example.vue
<template>
<div>
{{isLoading}}
{{getCustomers}}
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name: 'example',
created() {
this.$store.dispatch('fetchCustomers')
},
computed: {
...mapGetters([
'getCustomers',
'isLoading'
])
}
}
</script>
App.vue
<template>
<div id="app">
<example/>
</div>
</template>
<script>
import example from './components/example'
export default {
name: 'App',
components: {
example
}
}
</script>