A library using the Vue Composition API for remote data fetching with stale-while-revalidate caching strategy
npx @tessl/cli install tessl/npm-swrv@1.1.0swrv (pronounced "swerve") is a library using the Vue Composition API for remote data fetching with stale-while-revalidate caching strategy. It enables developers to create fast, reactive UIs by returning cached data immediately while simultaneously fetching fresh data in the background.
npm install swrvimport useSWRV, { mutate, SWRVCache, IConfig } from "swrv";For CommonJS:
const useSWRV = require("swrv");
const { mutate, SWRVCache } = require("swrv");import useSWRV from "swrv";
export default {
setup() {
const { data, error, isValidating, mutate } = useSWRV('/api/user', fetch);
return {
data,
error,
isValidating,
mutate
};
}
};swrv is built around several key components:
useSWRV composable that provides reactive data fetching with automatic cachingCore composable for reactive data fetching with automatic caching, revalidation, and error handling.
function useSWRV<Data = any, Error = any>(
key: IKey
): IResponse<Data, Error>;
function useSWRV<Data = any, Error = any>(
key: IKey,
fn: fetcherFn<Data> | undefined | null,
config?: IConfig
): IResponse<Data, Error>;Global mutation function and cache management for coordinating data updates across components.
function mutate<Data>(
key: string,
res: Promise<Data> | Data,
cache?: SWRVCache<any>,
ttl?: number
): Promise<{data: Data, error: any, isValidating: boolean}>;Configurable cache implementations for storing fetched data with TTL support and automatic expiration.
class SWRVCache<CacheData> {
constructor(ttl?: number);
get(k: string): ICacheItem<CacheData>;
set(k: string, v: any, ttl: number): void;
delete(serializedKey: string): void;
serializeKey(key: IKey): string;
}type IKey = keyType | WatchSource<keyType>;
type keyType = string | any[] | null | undefined;
type fetcherFn<Data> = (...args: any) => Data | Promise<Data>;
interface IResponse<Data = any, Error = any> {
data: Ref<Data | undefined>;
error: Ref<Error | undefined>;
isValidating: Ref<boolean>;
isLoading: Ref<boolean>;
mutate: (data?: fetcherFn<Data>, opts?: revalidateOptions) => Promise<void>;
}
interface IConfig<Data = any, Fn extends fetcherFn<Data> = fetcherFn<Data>> {
refreshInterval?: number;
cache?: LocalStorageCache | SWRVCache<any>;
dedupingInterval?: number;
ttl?: number;
serverTTL?: number;
revalidateOnFocus?: boolean;
revalidateDebounce?: number;
shouldRetryOnError?: boolean;
errorRetryInterval?: number;
errorRetryCount?: number;
fetcher?: Fn;
isOnline?: () => boolean;
isDocumentVisible?: () => boolean;
}
interface revalidateOptions {
shouldRetryOnError?: boolean;
errorRetryCount?: number;
forceRevalidate?: boolean;
}
interface ICacheItem<Data> {
data: Data;
createdAt: number;
expiresAt: number;
}