I have integrated Vuex with axios to retrieve data from my backend. However, I am facing an issue where the state property userName
is not updating within my Vue Single File Component(SFC).
approot.js state
const state = {
userName: 'foo'
};
getter
const getters = {
getUserName: (state) => state.userName
};
Single File Component
<template>
<div id="navbar">
//cut for brevity
<span>{{getUserName}}</span>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
name: 'navbar',
computed: mapGetters(['getNumberOfJobMessages','getUserName']),
//cut for brevity
}
</script>
<style scoped>
//cut for brevity
</style>
Action fetching data with axios from the backend
const actions = {
async fetchMenuData({ commit }) {
//fetch data from api controller
const response = await axios.get('../api/Menu/GetMenu');
console.log(response.data.userName); //not undefined
commit('setMenuData', response.data);
}
}
Mutation setting state variables
const mutations = {
setMenuData(state, menuData) {
console.log(menuData.userName); //not undefined
state.userName = menuData.userName;
console.log(state.userName); //not undefined
}
}
Problem Whenever my single file component calls getUserName, it consistently shows 'foo', the initial hardcoded value. This discrepancy is puzzling as all other state variables are updated correctly using the same method, and other components access them without any issues.
If anyone can pinpoint what might be going wrong or identify a flaw in my code, I would greatly appreciate the help.