Plugins
Prefetch
Preload data before it's needed
The prefetch plugin lets you load data ahead of time, so it's ready when the user navigates.
Installation
npm install @spoosh/plugin-prefetchUsage
import { prefetchPlugin } from "@spoosh/plugin-prefetch";
import { cachePlugin } from "@spoosh/plugin-cache";
const plugins = [
prefetchPlugin(),
cachePlugin({ staleTime: 5000 }),
];
// prefetch is returned from createReactSpoosh
const { useRead, useWrite, prefetch } = createReactSpoosh(spoosh);Basic Prefetch
// Prefetch data
await prefetch((api) => api.posts.$get());
// Prefetch with query parameters
await prefetch((api) => api.posts.$get({ query: { page: 1, limit: 10 } }));Prefetch with Options
Pass plugin options as the second argument:
await prefetch(
(api) => api.users[userId].$get(),
{
staleTime: 60000,
retries: 3,
}
);Prefetch on Hover
A common pattern is prefetching when the user hovers over a link:
<Link
href="/posts/1"
onMouseEnter={() => prefetch((api) => api.posts[1].$get())}
>
View Post
</Link>Prefetch on Route Change
Prefetch data before navigating:
async function handleNavigation(postId: number) {
await prefetch((api) => api.posts[postId].$get());
router.push(`/posts/${postId}`);
}Options
Plugin Config
| Option | Type | Default | Description |
|---|---|---|---|
staleTime | number | - | Default stale time for prefetched data (ms) |
Prefetch Options
The second argument accepts any plugin options plus:
| Option | Type | Description |
|---|---|---|
tags | string[] | Custom cache tags |
additionalTags | string[] | Additional tags to append |