Cache / Preload
You can enable the cache function by setting cacheKey
. When the cache is enabled, VueRequest will cache the current request's result and wait until the component is initialized or another set of the same cacheKey
. When the request is initialized, the cached data will be returned first if there is a cache. Then a new request will be initiated behind the scenes. This ensures that the data is presented to the user with the fastest data. This is also an implementation of preloading.
CacheTime
You can also set the recovery time of the cache. When the time to cache data exceeds the set cacheTime
(the default is 600000 milliseconds, which is 10 minutes), VueRequest will automatically discard the cached data. After the next request is initiated, the new data is cached again.
const { data } = useRequest('api/date', {
cacheKey: 'date',
cacheTime: 300000, // 5 minutes
});
StaleTime
Suppose you can ensure that the cached data will not be updated in a certain period. In that case, you can set a freshness time staleTime
(default is 0, That is, no preservation). When the preservation time is set, VueRequest will consider the cached data fresh within that time and not initiate new requests. This can relieve the pressure of requests for some regularly updated interfaces.
const { data } = useRequest('api/date', {
cacheKey: 'date',
staleTime: 3600000, // 60 minutes
});