Skip to content
Advertisement

Vuex 4, State is empty in component

I am trying to access subjects store state using this.$store.state.subjects inside my home component however it comes up as an empty array. Using console.log the only place I am able to see the state.subjects populated is if its in the mutation function. Anywhere else the console.log is empty. It seems to me that the state is not persisting from the mutations, but I’m not sure why.

I have tried quite a few stackoverflow answers however, non of them fix the issues or I have no clue what I am reading in the post. I have also left of code from my code blocks to make this post more readable, such as imports or templates.

Store index.js

JavaScript

Main.js

JavaScript

Home.vue

JavaScript

Advertisement

Answer

In the component, you’re copying the value of this.$store.state.subjects before the axios call has completed. Wait for the promise to resolve first. To do that, you’ll need to first return the promise from the action:

JavaScript

Waiting for the promise:

JavaScript

Better than this would be to remove subjects from your component data and use a computed instead to sync with the Vuex state:

JavaScript
JavaScript

Then you would only have to dispatch the action and the component will take care of the rest:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement