0
votes

If I am rendering a page with Nuxt, Vue, and Axios - is there a way to reuse the asyncData request (or data)?. For example, if I render a response, and the user takes an action on the page to filter, sort, etc. the data, can I reuse the same data to render again - or do I need to make a new call in mounted?

export default {
  asyncData ({ env, params, error }) {
    return axios.get(`${env.cockpit.apiUrl}/collections/get/cat_ruleset?token=${env.cockpit.apiToken}&simple=1&sort[ruleid]=1`)
      .then((res) => {
        return { catrules: res.data }
      })
      .catch((e) => {
        error({ statusCode: 404, message: 'Post not found' })
      })
  },
  mounted() {
  },
  methods: {
  }
}
1
I think you can store this data in vuex, then you can reuse without making new requests again.Suman Biswas
you could also move that async call into a method which will allow it to be reused.A. L
Just don't modify original data you may need later, make a copy.Estus Flask

1 Answers

0
votes

Of course you can reuse it. The simplest way would be to store the result somewhere (anywhere, really, but your store would be a good storage candidate) and change your method to:

asyncData ({ env, params, error }) {
  return X ? Promise.resolve(X) : axios.get(...)
}

... where X is the stored result of your previous call.

But you don't have to.

Because, by default, the browser will do it for you. Unless you specifically disable the caching for your call, the browser will assume making the same call to the server will yield the same result if you do it within the number of seconds set in max-age of Cache-control.

Basically, the browser returns the previous result from cache without making a call to the server, so the optimization you're after is already performed by the browser itself unless you specifically disable it.

You can easily spot which calls were served from cache and which from server by looking in the Network tab of DevTools in Chrome. The ones from cache will have (memory cache) in the Size column:

Image of cached resources

... and will have a value of 0ms in Time column.


If you want control over when to call the server and when to serve a cached result — most browsers have a limit on max-age (see link above) — you could (and should) store the result of your previous call and not rely at all on the browser cache (basically the internal check inside the method, which I suggested at the top).
This would enable you to avoid making a call long time after the cache max-age has passed, because you already have the data, should you choose to do so.