[Vuejs]-How to deduplicate data fetches in children routes

1👍

Use vuex for state management. For example, setting something like lastUser and userData which could be accessed from any component. fetchUser would then be an action in the store:

Store

state: {
  lastUser: '',
  userData: null
},
actions: {
  fetchUser({ state }, user) {
    if (state.userData && user == state.lastUser) {
      return state.userData;
    } else {
      // Api call, set userData and lastUser, return userData
    }
  }
}

User

async created() {
  this.user = await this.$store.dispatch('fetchUser', this.$route.params.id);
}

UserEdit

async created() {
  this.user = await this.$store.dispatch('fetchUser', this.$route.params.id);
}
👤Dan

Leave a comment