VueJS - Can't assign value from mapState to data property after reloading the page

Viewed 1934

Can't assign the value from mapState to data property after reloading the page, it works if you go to the child page but not if you are already standing in the child page and reloading the browser.

Computed mapState

computed: {
  ...mapState({
    tsStore: state => state.SchemeStore
  })
}

Data Property

data () {
  return {
    works: '',
    offTime: '',
  }
}

Mounted

if (this.tsStore.singleView) {
  // Set data based on api.
  let single = this.tsStore.singleView
  this.works = single.works
  this.offTime = single.offTime
}

After reloading works and offTime get empty in the data property.

1 Answers

Yes, the problem is the state being updated after the component was mounted; So, the updated method is called instead of mounted. It is visible in this fiddle, where the API call is simulated by the setTimeout:

https://jsfiddle.net/eywraw8t/369915/

I think the best way to get the component updated is using computed properties, where Vue implements proxies to watch for changes, like this fiddle:

https://jsfiddle.net/3mn2xgvr/

I moved the changes to a computed properties so when the state in Vuex changes, all data that depends on that changes.

Related