Search code examples
vue.jsvuex

What is the best way to fetch multiple stores (from server) at once, instead fetching them one by one?


I have multiple stores like categories, units, currencies. In my project after a successful login I fetch them one by one.

store.getters['category/isReady'] || store.dispatch('category/fetchCategories');
store.getters['currency/isReady'] || store.dispatch('currency/fetchCurrencies');
store.getters['unit/isReady'] || store.dispatch('unit/fetchUnits');

So for each I make a axios request, get the data and store it. But instead I want to make one request and get all of them and then store them at once.

PS: By the way I use namespaced modules for each store I have mentioned.


Solution

  • Thanks to @tony19 and @Daniel_Knights I now use a single request to set all my initial data from server side. After I receive the server response I store them for each module.

    So within my store root (store/index.js)

    modules: ...
    actions: {
        initialize(ctx){
            axios.get(process.env.API_URL + "provide/initials")
                .then((response) => {
                    ctx.dispatch('category/setFlat', response.data.flat);
                    ctx.dispatch('category/setNest', response.data.nest);
                    ctx.dispatch('currency/set', response.data.currencies);
                    ctx.dispatch('unit/set', response.data.units);
                    ...
                })
                .catch((e) => {
                    return { status: 'error', message: 'Problem occurred.', orinigal: e };
                });
            }
        },
    ...
    

    While I before dispatched each module, now I just dispatch the root module store.dispatch('initialize'); and thats it