Kaustubh Parab
Kaustubh Parab

Reputation: 133

Storage not working properly in vuex axios response

Whenever i dispatch data to vuex storage using axios response, for eg.

** 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 response
        _this.$store.dispatch('setUserRoles', response.data.data)
      }
    }
    check_role(){

    }
  }

and When i console in sidebar like console.log(this.$store.state.userStore.roles) it have value, but when i console in dashboard it return null and when i see vuex chrome extension it contains value (provided image below), but in dashboard it return null

eg in dashboard 

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

enter image description here

Now when i dispatch to vuex outside the axios response it works perfectly and gives value in dashboard but its throw error like Error: [vuex] Do not mutate vuex store state outside mutation handlers. for eg.

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)
  }
}

eg in dashboard it give value if i use dispatch outside axios

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

Am i missing something???

Upvotes: 4

Views: 725

Answers (2)

Vladislav Ladicky
Vladislav Ladicky

Reputation: 2489

Try this:

created () {
  this.getRoles()
},

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

And do not try to console roles in created method. Because it can't work, axios is async, you will console state before data arrives. If, console it in axios callback too:

created () {
  this.getRoles()
},

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

Upvotes: 2

Bharathkumar kamal
Bharathkumar kamal

Reputation: 211

You are trying to console store.state.userStore.roles before api call is made. Avoid accessing store value in created()

Upvotes: 0

Related Questions