Mathieu Mourareau
Mathieu Mourareau

Reputation: 1220

Vuex update state

When I'm calling a Vuex action and perform an axios request, it's not updating all my localStorage item, it's very strange.

My axios request could return objects or an empty collection and I would like to update all the time my userDailyFoods item. I console log my mutation and getter and it works but for the update of the localStorage item it's bugging. Sometimes I get the result, sometimes not.

What am I doing wrong ?

action:

updateUserDailyFoods(context, data) {
  let date = data.data
  if (date) {
    axios.get(`/user/daily/food/${context.getters.user.id}/${date}/`).then(r => {
      context.commit('userDailyFoods', {
        userDailyFoods: r.data.data
      });
      localStorage.setItem('userDailyFoods', JSON.stringify(r.data.data));
    }).catch(e => {
      console.log(e)
    })
  }
  console.log(localStorage.getItem('userDailyFoods'));
}

mutation:

userDailyFoods (state, payload) {
  if(payload) {
    state.userDailyFoods = payload.userDailyFoods
  }
},

getter:

userDailyFoods(state){
  return state.userDailyFoods
}

state:

userDailyFoods: JSON.parse(localStorage.getItem('userDailyFoods')) || [],

UPDATED

when i go to my view component

computed: {
  userDailyFoods() {
    return this.$store.state.userDailyFoods
  },
}

and I console log my action:

console.log(this.userDailyFoods)

then the result is updated after two clicks, not only one.

getDaySelected(day) {
  var day = moment(day).format('YYYY-MM-DD');
  this.$store.dispatch('updateUserDailyFoods', {
    data: day
  })
  console.log(this.userDailyFoods)
  this.$parent.$data.foods = this.userDailyFoods
}

Upvotes: 1

Views: 301

Answers (1)

Dan
Dan

Reputation: 63059

(Answer as requested) The value is probably being set in localStorage every time, but you're trying to log it before the async Axios operation has completed. Move the console.log into the then block:

.then(r => {
    context.commit('userDailyFoods', {userDailyFoods: r.data.data});
    localStorage.setItem('userDailyFoods', JSON.stringify(r.data.data));
    console.log(localStorage.getItem('userDailyFoods'));
})

Axios (and AJAX in general) is asynchronous which means that the operation begins separately from the normal synchronous flow of code. After it begins, program execution immediately resumes, often before the async operation is complete. At the time you are logging to the console, there is no guarantee that this async promise is resolved yet.

As an aside, there is no need for that getter, which you can think of as a computed that isn't computing anything.

Upvotes: 1

Related Questions