Resource preloaded was not used by SWR
See original GitHub issueBug report
Description / Observed Behavior
When using <link rel='preload' />
prefetching, the following warning occurs in Mozilla Firefox 87.0 (on Pop_OS! 20.04):
The resource at “http://localhost:3000/api/account” preloaded with link preload was not used within a few seconds. Make sure all attributes of the preload tag are set correctly.
Expected Behavior
SWR should use the prefetched data and that warning should not occur. I’m guessing that the reason why the data wasn’t used by SWR is because I’m using axios
(which, in turn, uses XMLHttpRequest
) in my SWR fetcher function (instead of using the browser built-in fetch
function). If this is the case, you should definitely add it to the documentation.
Repro Steps / Code Example
I followed the docs on preloading data and added the following:
<Head>
<link rel='preload' href='/api/account' as='fetch' />
</Head>
I then use SWR to fetch that data client-side (using axios
which uses XMLHttpRequest
under the hood):
const { data } = useSWR<UserJSON>('/api/account', fetcher);
That fetcher
function is defined as the following:
export async function fetcher<T, D = T>(
url: string,
method: 'get' | 'put' | 'post' | 'patch' | 'delete' = 'get',
data?: D
): Promise<T> {
const headers: Record<string, string> = {};
if (typeof data === 'string') headers['Content-Type'] = 'text/plain';
const [err, res] = await to<AxiosResponse<T>, AxiosError<APIErrorJSON>>(
axios({ method, url, data, headers })
);
if (err && err.response) {
const msg = `API (${url}) responded with error: ${err.response.data.message}`;
throw new APIError(msg, err.response.status);
} else if (err && err.request) {
throw new APIError(`API (${url}) did not respond.`);
} else if (err) {
throw new APIError(`${err.name} calling API (${url}): ${err.message}`);
}
return (res as AxiosResponse<T>).data;
}
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (1 by maintainers)
@nicholaschiang The example in the documentation has a
crossorigin
attribute, but your code doesn’t.https://swr.vercel.app/docs/prefetching#top-level-page-data
I think the
crossorigin
attribute is necessary to preload a fetch request.https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload#cors-enabled_fetches
We now have a preload API in SWR that covers this case better, check out the release: https://github.com/vercel/swr/releases/tag/2.0.0-beta.4
It will be documented with the upcoming 2.0 stable release.