Only make API call when data in Vuex store is "stale" or not present

Viewed 1789

I am using Vuex for state management in my VueJS 2 application. In the mounted property of my component in question I dispatch an action...

mounted: function () {
  this.$store.dispatch({
    type: 'LOAD_LOCATION',
    id: this.$route.params.id
  });
}

...and this action uses axios to make an API call and get that location's details.

LOAD_LOCATION: function ({ commit }, { id }) {
  axios.get(`/api/locations/${id}`).then((response) => {
    commit('SET_LOCATION', { location: response.data })
  }, err => {
    console.log(err);
  });
}

The mutation looks like so:

SET_LOCATION: (state, { location }) => {
  state.locations.push(location);
}

This makes complete sense the first time this location is navigated to. However, let's say a user navigates to /locations/5 then navigates elsewhere in the app and returns to /locations/5 a few minutes later. Would it be a good idea to check for the location in state.locations and only make the API call if this location is not present? Or even better, to check the "staleness" of the location data and only make the API call to refresh the data after a certain period has passed?

Edit: Is there a pattern that is typically followed for these cases with Vuex? It seems to be a common case, but I'm not sure if jamming the logic to check for presence/staleness in the action is a solid approach.

1 Answers
Related