CodexBloom - Programming Q&A Platform

Handling AJAX requests with Vue.js and Vuex: State implementation guide after API call

👀 Views: 137 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-19
vue.js vuex axios javascript

I'm trying to configure I've been banging my head against this for hours. I'm working on a personal project and I'm stuck on something that should probably be simple. I'm having trouble with my Vue.js application where I'm making an AJAX call using Axios to fetch data from my REST API, and while the response is correctly logged in the console, my Vuex state isn't updating as expected. Here's the code for my action in Vuex: ```javascript // store.js import axios from 'axios'; const store = new Vuex.Store({ state: { items: [] }, mutations: { SET_ITEMS(state, items) { state.items = items; } }, actions: { fetchItems({ commit }) { return axios.get('https://api.example.com/items') .then(response => { console.log('Response data:', response.data); commit('SET_ITEMS', response.data); }) .catch(behavior => { console.behavior('There was an behavior!', behavior); }); } } }); ``` In my Vue component, I'm trying to dispatch this action: ```javascript // MyComponent.vue <template> <div> <ul> <li v-for="item in items" :key="item.id">{{ item.name }}</li> </ul> </div> </template> <script> import { mapState } from 'vuex'; export default { computed: { ...mapState(['items']) }, created() { this.$store.dispatch('fetchItems'); } } </script> ``` When I inspect the Vuex state after the AJAX call, the items array remains empty, even though the console logs show that the API call was successful and returned data. I've ensured that I'm correctly mapping the state to the component, and I can see that the `fetchItems` action is being called. I've also tried using `this.$store.commit` directly within the component to see if that would work, but it didn't help. I'm using Vue.js version 2.6 and Vuex version 3.1. Can anyone point out what I'm missing here or suggest a better approach for debugging this scenario? My development environment is Ubuntu 20.04. Thanks for taking the time to read this! This is my first time working with Javascript LTS. Thanks, I really appreciate it! I'm using Javascript LTS in this project. For reference, this is a production REST API.