Cache & SWR
If options.cacheKey is set, useRequest will cache the successful data . The next time the component is initialized, if there is cached data, we will return the cached data first, and then send a new request in background, which is the ability of SWR.
You can set the data retention time through options.staleTime. During this time, we consider the data to be fresh and will not re-initiate the request.
You can also set the data cache time through options.cacheTime, after this time, we will clear the cached data.
Next, through a few examples to experience these features.
SWR
Keep your data fresh
Data sharing
The content of the same cacheKey is shared globally, which will bring the following features
- Sharing request Promise, only one of the samecacheKeywill initiate a request at the same time, and the subsequent ones will share the same requestPromise.
- Data synchronization. At any time, when we change the content of one of the cacheKey, the content of the othercacheKeywill be synchronized. In the following example, the two components will only initiate one request during
Parameters cache
The cached data includes data and params. Through the params caching mechanism, we can remember the conditions of the last request and initialize it next time.
Clear cache
provides a clearCache method, which can clear the cache data of the specified cacheKey.
Custom sync cache
By setting setCache and getCache, you can customize the cache, for example, you can store data in localStorage, IndexDB, etc.
Please note
- setCacheand- getCacheneed to be used together.
- In the custom cache mode, cacheTimeandclearCachewill be unused, please implement it yourself according to the actual situation.
Custom async cache
Example localforage 、 indexDB.
API
interface CachedData<TData, TParams> {
  data: TData
  params: TParams
  time: number
}
interface CachedData<TData, TParams> {
  data: TData
  params: TParams
  time: number
}
Options
| Property | Description | Type | Default Value | 
|---|---|---|---|
| cacheKey | A unique ID of the request. If cacheKeyis set, we will enable the caching mechanism. The data of the samecacheKeyis globally synchronized. | string | - | 
| cacheTime | 
 | number | 300000 | 
| staleTime | 
 | number | 0 | 
| setCache | 
 | (data: CachedData) => void; | - | 
| getCache | Custom get cache | (params: TParams) => CachedData | - | 
clearCache
import { clearCache } from 'vue-hooks-plus/es/useRequest';
clearCache(cacheKey?: string | string[]);
import { clearCache } from 'vue-hooks-plus/es/useRequest';
clearCache(cacheKey?: string | string[]);
- Support clearing a single cache, or a group of caches
- If cacheKeyis empty, all cached data will be cleared
Remark
- Only successful request data will be cached
- Cached data includes dataandparams