I am using useRequest from ahooks library. I specified cacheKey in options but the same request is repeated over and over when it is supposed to be retrieved from cache.
let someVar = 'someValue'
const { data, loading } = useRequest(
async () => someRequestThatDependOnVariable(someVar),
{
refreshDeps: [someVar],
cacheKey: `request-${someVar}`,
},
);
someVar is updated via select field
but the same request is repeated over and over when it is supposed to be retrieved from cache.
This is as designed.
According to the documentation:
If
options.cacheKeyis set,useRequestwill 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
So the point of cacheKey here is to hide the loading of data by showing previously cached data while the latest data is being fetched. This does not prevent the data from being loaded.
However, if you also use the staleTime property, you can tell it not to make a new query for some number of seconds from the last successful request.
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.
const { data, loading } = useRequest(
async () => someRequestThatDependOnVariable(someVar),
{
refreshDeps: [someVar],
cacheKey: `request-${someVar}`,
staleTime: 10 * 60 * 1000 // 10 minutes in milliseconds
},
);