mikeym
mikeym

Reputation: 6311

Vuex store getter returns [__ob__: Observer] on page refresh

Given the following code my Veux store getter returns [__ob__: Observer] whenever I refresh the page. I am using Vue 2.2.3 and TypeScript.

The data loads correctly on first load, which is coming from an external API, but when using the getter it fails and the API must be called again to retrieve the page data.

Here is the console log after initial page load.

[{…}, {…}, {…}, {…}, __ob__: Observer]

There are 4 objects, which is correct, and the data is displayed on the page. However I don't know why there is an Observer added to the end.

Given that the getter works on first load, I know that the setter which adds the data to the store after retrieving from the API also is working correctly.

The same console log produces only the Observer when I refresh the page.

[__ob__: Observer]

This is what the getter in my store looks like.

get getItems() {
  console.log('Store items -> ', this.items) // return empty array on page refresh
  // Suggested solution from another SO question 
  var parsedObj = JSON.parse(JSON.stringify(this.items)) 
  return parsedObj
}

As shown above, I have tried the solution proposed in this question, but it still doesn't work.

The component using the store has a pretty basic getter call. Again this works fine on first page load but not after refresh.

async created() {
  const result = await myModule.getItems
  console.log('[dev page] items from store -> ', result) // empty on refresh
  this.fmData = result 
  console.log('fm in Created -> ', this.fmData) // Observer only on refresh
}

I know Pinia would probably be a better store solution today, but unfortunately I am stuck with Vuex on this project for the moment.

I am unsure how to remedy this issue from here.

Upvotes: 3

Views: 736

Answers (2)

hoomi
hoomi

Reputation: 139

At least in my case, after spending few hours, I figured out that you must set the value in the store using actions that calls the mutations. Example:

mutations: {
    setUserId(state, id) {      
        state.activeUserId = id;
    }
},
actions: {
    updateUserId: ({commit, state}, id) => {
        commit('setUserId', id)
        return state.activeUserId;
    }
}

When I was using just the mutation, I got observer, when I added the action, the issue was resolved and I could access the this.$store.state.activeUserId from any view.

Upvotes: 0

kissu
kissu

Reputation: 46642

If you use any store (Vuex or Pinia), there will be no persistency by default. Those things are not to be handled by Vue anyway. Hopefully, there is plenty of extensions for both store that will allow that.

Here is my previous answer with all the relevant links.

Upvotes: 1

Related Questions