[Vuejs]-How to load data into a vuex module only when it's needed? problems with async/await

0👍

Your components should not care about how many times they request a resource, neither should the userRolesApi I think. If eventually you use fetch then you can cache the promise as long as it’s not resolved or rejected and later requests will just return that promise.

const fetchOnce = ((cache) => (url, config) => {
    const cacheKey = `${JSON.stringify(config)} ${url}`;
    if (!cache[cacheKey]) {
        cache[cacheKey] = axios.get(url, config)
            .then((result) => {
                delete cache[cacheKey];
                return result;
            })
            .catch((error) => {
                delete cache[cacheKey];
                return Promise.reject(error);
            });
    }
    return cache[cacheKey];
})({});

Leave a comment