Honoring Cache-Control Header #559
-
I am brand new to the library and have a very basic question about caching strategy. I have seen the API options for triggering manual and automatic revalidation, but does swr honor the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
When Going back to your particular use case, you could roll your own solution in your const handles = new Map<string, number>();
const fetcher = async (key: string) => {
const response = await fetch(key);
clearTimeout(handles.get(key));
const cacheControl = parseCacheControlHeader(response.headers.get("cache-control"));
if (cacheControl.maxAge > 0) {
const handle = window.setTimeout(() => {
mutate(key);
}, cacheControl.maxAge * 1000);
handles.set(key, handle);
}
return response.json();
}; This'll cause any resources fetched with this particular |
Beta Was this translation helpful? Give feedback.
-
I think I am getting it now. The triggers simply activate And incidentally, this would explain why the documentation uses "revalidate" vs "refetch." Because one does not always imply the other as whether revalidation results in an actual refetch from the server is at the discretion of the fetcher. |
Beta Was this translation helpful? Give feedback.
useSWR
requires users to pass afetcher
function having the type signature(key: string) => Data | Promise<Data>
to 'get' the data so thereforeuseSWR
itself doesn't know anything about your cache headers, just thedata
and thekey
it belongs to.useSWR
will cache thedata
until new data comes back to replace it, with fetches being triggered by revalidation events such asrevalidateOnMount
,revalidateOnFocus
, or manualmutate
invalidations, for example.When
swr
tries to revalidate/fetch the resource via yourfetcher
caused by one of those events, yourfetcher
could make a HTTP request and then it'll go through your browsers HTTP cache at that point.Going back to your particular use case…