0
votes

At work, we think about using Vuejs with Vuex for our frontend. I have already used it for private projects.

One of our big questions is the traffic. Our platform needs a lot of data, sometimes in large packages. Some of them are really big and it would be more expensive to load them more than once.

I've seen many examples of vue with vuex, but for me it looked like all the samples would request the same (already loaded) data every time they paged.

My real question is: Is there a way in vuejs or general to avoid or solve this problem? The only helpful thing I have found so far was this.

2

2 Answers

1
votes

As far as I know, you can use this library https://github.com/kuitos/axios-extensions

An example here

import Axios from 'Axios';

import { throttleAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 2 * 1000 })
});

http.get('/users'); // make real http request
http.get('/users'); // responsed from the cache
http.get('/users'); // responsed from the cache

setTimeout(() => {
    http.get('/users'); // after 2s, the real request makes again
}, 2 * 1000)

As you can see, you can create an adaptor and custom what you want. For example here, you keep the cache for only 2 seconds. So the first request to /users is a real one. The second and thirst request are cache, and the last one is after the two seconds, so it's a real one.

Can you be more specific about the context of how you will keep the cache. When do you need to reload the cache, after how many times, after which event, ...?

1
votes

The strategy I use is to store the value on the Vuex state.

I write all my request in Vuex actions. In every action, I check if the data already exists on the Vuex state. If it does, I simply bypass the request and return the data from the state (saving requests from being called multiple times). If it doesn't exist, I'll make the request, then store the result on the Vuex state, and return the value.

Vuex Action:

getLists({ state, commit }) {
  return new Promise((resolve, reject) => {
    if (state.isSetLists === false) {
      getListsFromServer((error, data) => {
        if (error) {
          reject(error);
        } else {
          console.log('call to getLists successful:', data);
          commit('setLists', data.lists);
          resolve(data.lists);
        }
      });
    } else {
      resolve(state.lists);
    }
  });
},

Then, the setLists mutation handles it like so:

setLists(state, lists) {
  state.isSetLists = true;
  state.lists = lists;
},

This way, the user can page around all they want, and only ever call each request once.