A
A
aheadweb2020-07-12 12:23:37
JavaScript
aheadweb, 2020-07-12 12:23:37

Getting asynchronous data from one module to another?

There are 2 modules in Vuex.
Module A receives data from the server and puts it in its store. Module B must take data from module A.
The problem is that when I knock from Module B through a getter or action on module A and ask to show me the data in the store, they are not there yet, i.e. they did not come from the server.

Module A

import {getProducts} from "../api";

export default {
    state: {
        products: [],
    },

    mutations: {
        setProducts(state, products) {
            state.products = products;
        }
    },

    getters: {
        getProducts({products}) {
            return products;
        },

    },

    actions: {
        async fetchProducts({commit}) {
            commit("setProducts", await getProducts());
        },
    }
}


Module B

export default {
    state: {
        size: 10,
        listProduct: [],
    },
    mutations: {
        setListProducts(state,payload) {
            console.log(payload)
        }
    },
    getters: {
        listProducts(state) {
            return state.listProduct;
        },
        getAllItemsFromProductsStore(_, getters, rootState) {
            return rootState.products.products;
        }
    },
    actions: {
        setListProducts({getters, commit}) {
            let localProducts = getters.getAllItemsFromProductsStore;
        }
    }
}


Actually, the question is how to properly implement the receipt of data from one module to another, so that the getter \ action already returns data after the response arrives from the server of module A?

As an option, I suppose in the component methods to re-request the action of module B until module A returns a NOT empty array. But how correct is this option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-07-12
@Aetae

In getter - no way. In action, just run module A's action and await it. In order not to run the action of module A several times, you can additionally do a proxy-caching action-shim, which will run the desired action once and until there is a response, return the Promise of the current one to all subsequent requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question