Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
createSwr
✓ import { createSwr } from 'swrev';
✗ const createSwr = require('swrev');
SWRev is primarily designed for modern JavaScript environments and ES Modules. While CommonJS `require` might technically work via transpilation, native ESM imports are the idiomatic way to consume it.
SWRConfig
✓ import { SWRConfig } from 'swrev';
✗ import SWRConfig from 'swrev';
Configuration utilities are typically named exports, not default. Ensure named import for `SWRConfig`.
mutate
✓ import { mutate } from 'swrev';
The `mutate` function is used for programmatic cache invalidation and updates. It is a named export.
This quickstart demonstrates how to initialize SWRev, perform data fetching using the SWR pattern, and manually mutate the cache. It showcases both direct SWR instance creation and global configuration.
import { createSwr, SWRConfig, mutate } from 'swrev';
interface UserData {
id: number;
name: string;
email: string;
}
// A generic fetcher function
const fetcher = async (url: string): Promise<UserData> => {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return response.json();
};
// Create an SWR instance with a default config
const { useSwr } = createSwr({
fetcher: fetcher,
revalidateOnFocus: true,
revalidateIfStale: true,
// Custom cache implementation (optional)
// cache: new Map()
});
async function simulateDataFetching() {
const userId = 1;
const userUrl = `https://jsonplaceholder.typicode.com/users/${userId}`;
console.log('Fetching user data with SWR...');
// First call: data will be fetched and cached
const { data: initialData, error: initialError, isValidating: initialValidating } = await useSwr<UserData>(userUrl);
if (initialError) {
console.error('Initial fetch error:', initialError);
} else {
console.log('Initial data:', initialData?.name);
}
// Simulate a subsequent read (should return stale data immediately if cached, then revalidate)
console.log('Fetching again (should be fast if cached)...');
const { data: subsequentData, isValidating: subsequentValidating } = await useSwr<UserData>(userUrl);
console.log('Subsequent data (stale or fresh):', subsequentData?.name);
if (subsequentValidating) {
console.log('Revalidating in background...');
// In a real app, you'd have a way to observe changes (e.g., framework hooks)
// For this example, we'll just wait a bit.
await new Promise(resolve => setTimeout(resolve, 1000));
const { data: freshData } = await useSwr<UserData>(userUrl);
console.log('Data after revalidation:', freshData?.name);
}
// Manually mutate the cache for a different key
const postId = 10;
const postUrl = `https://jsonplaceholder.typicode.com/posts/${postId}`;
console.log('Mutating cache for a post...');
await mutate(postUrl, { id: postId, title: 'Mutated Title', body: 'Mutated Body', userId: 1 });
const { data: mutatedPost } = await createSwr().useSwr(postUrl);
console.log('Mutated post data:', (mutatedPost as any)?.title);
console.log('\nDemonstrating global configuration:');
// You can also use a global SWRConfig for all instances
SWRConfig.setDefault({
fetcher: async (key: string) => {
console.log(`Global fetcher for: ${key}`);
const res = await fetch(key);
return res.json();
}
});
const anotherUserUrl = `https://jsonplaceholder.typicode.com/users/2`;
const { data: user2 } = await createSwr().useSwr<UserData>(anotherUserUrl);
console.log('User 2 fetched with global config:', user2?.name);
}
simulateDataFetching();
Errors
Common errors & fixes
TypeError: (0 , swrev__WEBPACK_IMPORTED_MODULE_0__.useSwr) is not a function
Attempting to import `useSwr` directly as a named export from 'swrev' instead of destructuring it from the object returned by `createSwr()`.
fixThe `useSwr` function is created by calling `createSwr()`. Correct usage is `const { useSwr } = createSwr();` or `const { useSwr } = createSwr({ /* config */ });`. Property 'name' does not exist on type 'unknown'.
TypeScript error when accessing properties on `data` without proper type assertion or generic type parameter in `useSwr`.
fixProvide a generic type argument to `useSwr` to inform TypeScript about the expected data structure, e.g., `const { data } = useSwr<UserData>(key, fetcher);`. Audit
Dependencies
No dependency data recorded yet.