Search code examples
vue.jsaxiosvuexnuxt.js

Copy of store not updated when mounted Async axios


I have been struggling with this issue for a day now. I want to make a copy of the store for user into userCopy so that it can be edited by the user without causing a mutation. My problem is that even though I am using the mounted hook, userCopy only returns an empty store state.

pages/settings/_id.vue

<template>
  <div>
    {{ user }} // will display the whole object 
    {{ userCopy }} // will only display empty store object
  </div>
</template>

<script>
import { mapState } from 'vuex'
import _ from 'lodash'

data() {
  return {
    userCopy: {}
  }
},

computed: {
   ...mapState({ user: (state) => state.staff.user })
},
created() {
   this.$store.dispatch('staff/fetchUser', this.$route.params.id)
},

mounted() {
   this.$data.userCopy = _.cloneDeep(this.$store.state.staff.user)
},
</script>

store/staff.js

import StaffService from '~/services/StaffService.js'
export const state = () => ({
  user: {
    offers: '',
    legal: ''
  }
})
export const mutations = {
  SET_USER(state, user) {
    state.user = user
  },
}

export const actions = {

  fetchUser({ commit, getters }, id) {
    const user = getters.getUserById(id)

    if (user) {
      commit('SET_USER', user)
    } else {
      StaffService.getUser(id) // StaffService users axios get call
        .then((response) => {
          commit('SET_USER', response.data)
        })
        .catch((error) => {
          console.log('There was an error:', error.response)
        })
    }
  },

}

export const getters = {
  getUserById: (state) => (id) => {
    return state.staff.find((user) => user.id === id)
  }
}

Even using this mounted method did not solve the issue. The userCopy object still returns empty.

 mounted() {
    this.$store
      .dispatch('staff/fetchUser', this.$route.params.id)
      .then((response) => {
        this.userCopy = this.$store.state.staff.user
      })
  },

Solution

  • It seems that the mounted() is called before your network request get solved. To fix this, I suggest to do like this. First:

    if (user) {
       console.log('user found',user)
      commit('SET_USER', user)
      return user
    } else {
        console.log('user not found')
    
        //RETURN the Axios Call here
        return StaffService.getUser(id) // StaffService users axios get call
        .then((response) => {
          commit('SET_USER', response.data)
    
          //return the response here, after committing
          return response.data
        })
    

    then in your component

     mounted() {
        this.$store
          .dispatch('staff/fetchUser', this.$route.params.id)
          .then((response) => {
            console.log(response)
            this.userCopy = response
          })
      }