M
M
Michael2020-06-24 13:17:25
Vue.js
Michael, 2020-06-24 13:17:25

Is it necessary to check that the vuex state has already been loaded?

Greetings.
I have a repository where a list of cities is stored

export default new Vuex.Store({
  state: {
    cities: [],
  },
  mutations: {
    SET_CITIES(state, payload) {
      state.cities = payload;
    }
  },
  getters: {
    cities: (state) => {
      return state.cities;
    }
  },
  actions: {
    fetchAllCities(context) {
      axios.get('http://localhost:3000/cities', {
        })
        .then(response => {
            context.commit('SET_CITIES', response.data)
          });
    }
  },
  modules: {}
});

And I have two pages:
{
    path: "/cities",
    name: "Cities",
    component: () =>
      import(/* webpackChunkName: "landing" */ "../views/cities/List.vue")
  },
  {
    path: "/cities2",
    name: "Cities2",
    component: () =>
      import(/* webpackChunkName: "landing" */ "../views/cities/List2.vue")
  },

Both of these components, for their work, require $store.state.cities to be filled, so each one has:
created: function() {
      this.$store.dispatch('fetchAllCities');
  },

But doing so, it turns out that when switching between pages, we will again 1) make an Ajax request (we are not considering caching yet) 2) entering this data into the reactivity

system data, you need to do a check, such as calling such an action from the components:
actions: {
    fetchOnceAllCities(context) {
      if (this.state.cities.length) return; // <-----------
      // loading only one time:
      axios.get('http://localhost:3000/cities', {
        })
        .then(response => {
            context.commit('SET_CITIES', response.data)
          });
    }
  },

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin B., 2020-06-24
@Kostik_1993

Why are you asking us? This is your application. In general, what you are talking about most likely does not require re-upload, so yes, most likely, in your case, verification is needed!
Usually reloading requires lists that can change frequently. In your case, I think that the data is not updated more than once a day / month / year

E
Eduard07, 2020-06-24
@Eduard07

How to prevent re-execution of axios request?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question