Issue with storage functionality in Vuex Axios response

Every time I send data to the Vuex storage using an axios response, for example:

** Sidebar.vue **
  created(){
    this.getRoles();
  },
  methods: {
    getRoles(){
      var _this = this
      var roles = null
      this.$http.get('/api/userroles/userroles').then(function(response){
        // Passing data to Vuex within the response
        _this.$store.dispatch('setUserRoles', response.data.data)
      }
    }
    check_role(){

    }
  }

And when I console log in sidebar like console.log(this.$store.state.userStore.roles), it has a value. However, when I console log in dashboard, it returns null. Even though when I check the Vuex chrome extension, it shows that it contains a value (see image below), but on the dashboard it returns null.

For example, in dashboard 

** dashboard.vue **
created(){
  console.log(this.$store.state.userStore.roles)
  // null
},

https://i.sstatic.net/KFQKj.jpg

Now, when I dispatch to Vuex outside of the axios response, it works perfectly and gives a value in the dashboard, but throws an error like "Error: [vuex] Do not mutate Vuex store state outside mutation handlers." For example:

created(){
  this.getRoles();
},
methods: {
  getRoles(){
    var _this = this
    var roles = null
    this.$http.get('/api/userroles/userroles').then(function(response){
      _this.roles_data = response.data.data
    }
    _this.$store.dispatch('setUserRoles', _this.roles_data)
  }
}

For example, in the dashboard it gives a value if I use dispatch outside axios:

** dashboard.vue **
created(){
  console.log(this.$store.state.userStore.roles)
  // (25) [{…}, {…}, {…}, __ob__: Observer]
},

Am I overlooking something???

Answer №1

Give this a shot:

created () {
  this.fetchRoles()
},

methods: {
  fetchRoles () {
    this.$http
      .get('/api/userroles/userroles')
      .then(({data: {data}}) => {
        this.$store.dispatch('setUserRoles', data)
      })
  }
}

Avoid attempting to log roles in the created method. Since Axios is asynchronous, trying to log the state will happen before the data arrives. Instead, log it within the axios callback:

created () {
  this.fetchRoles()
},

methods: {
  fetchRoles () {
    this.$http
      .get('/api/userroles/userroles')
      .then(({data: {data}}) => {
        this.$store.dispatch('setUserRoles', data)
        // log roles here, not in the created method
        console.log(this.$store.state.userStore.roles)
      })
  }
}

Answer №2

Attempting to access store.state.userStore.roles to console it before making the api call is not recommended. It's best to avoid accessing the store value in the created() method.

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

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

Using Cordova for mobile applications to play local video files

Our iOS app, developed using PhoneGap / Cordova 4.3.0, loads an external website directly utilizing <content src="http://example.com/foo" /> in the config.xml file. All functionality resides within this website, eliminating the need for local HTML or ...

When running a callback function, the "this" of an Angular 2 component becomes undefined

One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data. The problem arises when attempting to use the callback function to append t ...

Unveiling Vue3: A Guide to Retrieving the Entire Component State, Along with its Properties, in the Vue Error Handler - Tips on Transforming a Vue Component Instance into

Incorporating Vue3 with the composition API and Bugsnag for error management has been a game-changer. When an error arises, my goal is to send the entire component state where the error occurred to Bugsnag (specifically, the object returned from setup()). ...

merge various useState functions for appending values to an array into a unified function in a React component

I am currently facing a challenge with code complexity. I have 8 arrays where I need to add items based on a button click. As of now, I have created 8 separate functions for each task. Is there a way to consolidate all these functions into one function tha ...

Having trouble with obtaining real-time text translation using ngx translate/core in Angular 2 with Typescript

Issue : I am facing a challenge with fetching dynamic text from a JSON file and translating it using the translate.get() method in Angular2. this.translate.get('keyInJson').subscribe(res => { this.valueFromJson = res; /* cre ...

Ways to eliminate all characters preceding a certain character within an array dataset

I am currently working on parsing a comma-separated string retrieved from a web service in my application, which contains a list of user roles. My goal is to convert this string into an array using jQuery, and I have successfully achieved that. However, I ...

What is the method for displaying a file using a binary string as input?

Is there a way to display a PDF file from a binary string on a web browser? I know that for image files, we can use atob() and then <img src="data:image/png;base64,... But what about PDF files? Is there an equivalent method or syntax like ReadItAs("cont ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

Unusual behavior exhibited by AngularJS when working with Float32Arrays

After working with Float32Array values in AngularJS, I have noticed some unexpected behavior. During my testing, I encountered the following scenarios: angular.module("myApp", []).controller("myCtrl", function($scope) { $scope.n = 0.2; // Displays as 0 ...

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

What is the best way to utilize Protractor to comb through a specific class, locate a p tag within that class, and validate certain text within it?

My current task involves using Protractor to locate a specific class and then search through all the p tags within that class to identify any containing the text "Glennville, GA". In my spec file, I have attempted the following steps: it('should fil ...

Deciding whether to implement Vuex in NUXT: A series of queries

I really appreciate NUXT framework, but it presents some challenges for me because we lack deep understanding of its underlying implementation and operational principles. I have a few questions regarding these concerns that I hope you can provide some guid ...

Instead of the typical Three.js pointer lock first person controls, how about experimenting with orbit

I'm struggling to understand why my controls are causing the camera to orbit around a fixed point instead of behaving like a first-person shooter game. After comparing my code to an example in the three.js documentation, I am aiming to replicate the ...

Enabling communication between JavaScript and PHP and vice versa

I am currently working on developing a Firefox plug-in with the purpose of gathering all the domains from the links located on the current site and showcasing their respective IP addresses. In order to achieve this, I have written JavaScript code that incl ...

Modifying static content within jQuery tabs

Encountering an issue with jQuery $('#tabs').tabs();. When checking out the example on JSFIDDLE, I noticed that the content containing an external php file is always displayed, even when switching to other tabs. <li class="files"> < ...

How can I use JavaScript to capture the "MDCMenu:selected" event for the Menu Component in Material Design Web Components?

I am currently using the Material Design Web Components plugin known as "Menu." Once the menu is launched, my goal is to be able to effectively handle all possible ways a "menu item" can be selected. While adding an on-click event through my framework&apo ...

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

Steps for automatically playing the next song when a button is clicked

I have encountered a challenge in developing a music player. The issue lies in the loading of the next song when the user clicks the 'next' button. While the new data is successfully updated in both the state and render, the music does not automa ...

Is there a way to verify if an array has been initialized and holds a value simultaneously?

Is there a more concise and elegant way to check if ['pk'] exists in the first item of an array before executing certain tasks? The array may not always have data, leading to bloated code. I'm looking for a streamlined solution in Javascrip ...