Vuex state fails to reflect the updated data

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.

Answer №1

To modify data, utilize mutations and reserve other tasks for actions. For example:

Action:

const actions = {
   async fetchMenuData({ commit }) {
      const response = await axios.get('../api/Menu/GetMenu');
      let userName = response.data.userName;
      commit('setUserName', userName);
   }
}

Mutations should be used to update state values like so:

const mutations = {
    setUserName(state, userName) {        
       state.userName = userName;
    }
}

Remember to dispatch the fetchMenuData function.

I'm not entirely sure why this issue occurs, but I encountered this problem and resolved it using this approach.

Answer №2

 fetch('../api/Menu/GetMenu')
  .then(({ response }) => {
    updateUsername(response.name);
  }).catch(error => { });

It's recommended to handle the commit within the then() function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Tips for verifying the authenticity of JSON data within Laravel

Below is an example of the JSON data I am sending via Postman for the 'specification' field: { "specification": [ { "type": [ { "type": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone", ...

The variable "vehicles" being referenced in the rendering process is not defined within the Vue.js instance

New to Vue and php, I recently began following a tutorial on these technologies. While everything seems to be working fine, I encountered an error related to fetching vehicles. After some troubleshooting, it appears that the issue is not with the API call ...

Issue with React Ref: Invariant Violation when trying to addComponentAsRefTo

I'm encountering an issue while attempting to add a ref to a React component. The error message I'm seeing is as follows: invariant.js:39Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding ...

Obtain the model value using Yii jQuery and then proceed to submit the form

Within the _form.php view, there is a presence of $model and a CActiveForm $form. I implemented JavaScript code to compare the value of $model->publication_date with the current date. If they are identical, the form will be submitted automatically. Othe ...

From converting multiple dictionary JSON files into a pandas dataframe

I have a collection of online data in the following format: {"headers": {"ai5": "3356", "debug": null, "random": null, "sd": "7.6"}, "post": {"event": "ggstart", "ts": "1462"}, "params": {}, "bottle": {"timestamp": "2016-05-09 02:00:00.033775", "game_id" ...

Can you explain the functionality of this Sample AngularJS Infinite Scroll feature?

I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my ...

How can I retrieve a member of onActivityResult() in Android from a different function outside of it?

Below is the onCreate method that captures an image from the camera: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_driverregister); app = (MyApplication) getApplicati ...

In order to ensure that the multiselect bootstrap dropdown options drop outside of the div and prevent scroll bubbling, there are specific

I am trying to customize a bootstrap multiselect dropdown located within a div. You can find an example of what I'm working on at this link: http://jsfiddle.net/The_Outsider/8watL2L1/9/ In my design, I want the multiselect dropdown options to drop ou ...

Preventing specific characters from being entered by the first player during the game

let firstplayerturn = 1; if (firstplayerturn == 1) { value_input = document.getElementById("b1").value; if (value_input === "0") { alert("ERROR"); } firstplayerturn = 0; } else { } <input type="text" id="b1" class="box"> My expectation ...

Showing the contents of a 2D array using Vue

I'm struggling to understand this situation... The backend sends an API response containing a two-dimensional array: Team categories, with teams assigned to each category. The data is coming back correctly, but I can't seem to display it proper ...

AngularJs and graph representation

After attempting to generate charts using angular-chart, I followed all the necessary steps and requirements outlined in the documentation. However, upon completion, my canvas element failed to display any content. My HTML Layout: Here is a snippet of my ...

Struggling to organize data into a hierarchy using the D3.js nest function

Attempting to build a d3.js tree, I need my data to be in hierarchical form before using d3.treeLayout. Currently, here is what my json array looks like: var data = [ {"group":"1","price":"36599.88", "cy":"44260"}, {"group":"2","price":"36599 ...

Exploring the content of a file with multiple JSONObjects

I have been working on storing an arraylist of Objects in JSON format in a file. When a new arraylist appears, it converts the object into JSON format and appends it to the file. Encoding seems to work fine, but I encounter an exception while decoding it. ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

Utilizing JSON data to instantiate classes from a file

class Company: def __init__(self, company_id, name): self.company_id = company_id self.name = name In my programming project, I have a Python class called Company (as shown above). I am currently working on integrating companies into t ...

extract information from a JSON string with Java

[{"statusCode":200,"body":null,"string":"{\"authenticationResultCode\":\"ValidCredentials\",\"brandLogoUri\":\"http:\\\/\\\/dev.virtualearth.net\\\/Branding\\\/l ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

"Learn the best way to showcase images within Pusher's real-time chat application

Having trouble displaying images in real-time chat using Pusher. I am storing the images as BLOB but cannot display them on the client side using JavaScript. When the person who sends the message types, the image shows up fine, but on the receiver's s ...