### Install Dependencies with Yarn Source: https://github.com/kong/swrv/blob/master/examples/vite/README.md Use this command to install all project dependencies when using Yarn. ```sh yarn install ``` -------------------------------- ### Run Vite Development Server Source: https://github.com/kong/swrv/blob/master/examples/vite/README.md Execute this command to start the Vite development server and view your application. ```sh yarn dev ``` -------------------------------- ### Install SWRV for Vue 3 Source: https://github.com/kong/swrv/blob/master/docs/guide.md Use this command to install the latest version of swrv for Vue 3 projects. ```shell yarn add swrv ``` -------------------------------- ### Run the PWA Application Source: https://github.com/kong/swrv/blob/master/examples/pwa/README.md Starts the PWA application using Yarn. After running, visit http://localhost:8007/ to interact with the app and test offline capabilities. ```sh yarn serve ``` -------------------------------- ### Implement localStorage Cache with SWRV Source: https://github.com/kong/swrv/blob/master/docs/features.md This example shows how to configure SWRV to use `localStorage` as its cache adapter. This is useful for offline support. It also disables automatic retries on errors. ```javascript import useSWRV from 'swrv' import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage' function useTodos () { const { data, error } = useSWRV('/todos', undefined, { cache: new LocalStorageCache('swrv'), shouldRetryOnError: false }) return { data, error } } ``` -------------------------------- ### Install SWRV for Vue 2.6 and below Source: https://github.com/kong/swrv/blob/master/docs/guide.md Install the 0.9.x version of swrv for Vue 2.6.x and below. This version requires initialization with the external @vue/composition-api plugin. ```shell yarn add swrv@legacy ``` -------------------------------- ### Install SWRV for Vue 2.7 Source: https://github.com/kong/swrv/blob/master/docs/guide.md Install the 0.10.x version of swrv, compatible with Vue 2.7.x, which does not require the external @vue/composition-api plugin. ```shell yarn add swrv@v2-latest ``` -------------------------------- ### Build and Serve Service Worker Source: https://github.com/kong/swrv/blob/master/examples/pwa/README.md Builds the project, navigates to the distribution directory, and serves the static content with CORS enabled on port 8007. This is typically used for PWA service worker setup. ```sh yarn build cd dist # service static content from here npx serve --cors -p 8007 ``` -------------------------------- ### Basic swrv Usage in Vue Component Source: https://github.com/kong/swrv/blob/master/README.md Demonstrates how to use the useSWRV hook in a Vue component's setup function to fetch user data. It handles loading and error states, and uses a fetcher function to retrieve data. ```vue ``` -------------------------------- ### Integrate SWRV with Vuex in Vue 3 Source: https://github.com/kong/swrv/blob/master/docs/features.md This example shows how to use SWRV within a Vue 3 application and synchronize its data with a Vuex store. It demonstrates dispatching Vuex actions when data changes. ```vue ``` -------------------------------- ### Custom Cache Implementation with SWRVCache Source: https://context7.com/kong/swrv/llms.txt Extend `SWRVCache` to create custom cache adapters, such as one backed by `sessionStorage`. Override `get`, `set`, and `delete` methods to manage cache persistence and retrieval. ```typescript import SWRVCache, { ICacheItem } from 'swrv/dist/cache' import useSWRV from 'swrv' // Example: SessionStorage-backed cache class SessionStorageCache extends SWRVCache { private STORAGE_KEY: string constructor(key = 'swrv-session', ttl = 0) { super(ttl) this.STORAGE_KEY = key } get(k: string): ICacheItem | undefined { const store = sessionStorage.getItem(this.STORAGE_KEY) if (!store) return undefined const parsed = JSON.parse(store) return parsed[this.serializeKey(k)] } set(k: string, v: any, ttl: number) { const _key = this.serializeKey(k) const store = sessionStorage.getItem(this.STORAGE_KEY) const payload = store ? JSON.parse(store) : {} const now = Date.now() payload[_key] = { data: v, createdAt: now, expiresAt: ttl ? now + ttl : Infinity, } sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify(payload)) } delete(serializedKey: string) { const store = sessionStorage.getItem(this.STORAGE_KEY) if (!store) return const payload = JSON.parse(store) delete payload[serializedKey] sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify(payload)) } } // Use the custom cache const sessionCache = new SessionStorageCache('app-cache', 1800000) // 30 min const { data } = useSWRV('/api/profile', fetcher, { cache: sessionCache }) ``` -------------------------------- ### Dependent Fetching with SWRV Source: https://github.com/kong/swrv/blob/master/docs/features.md Fetch data that depends on other data using SWRV. This example demonstrates how to fetch user data first, and then use the user's ID to fetch their projects. SWRV ensures maximum parallelism and serial fetching when necessary. ```vue ``` -------------------------------- ### Vue Template Using useSwrvState Source: https://github.com/kong/swrv/blob/master/README.md Example of how to use the `useSwrvState` composable within a Vue template to conditionally render UI elements based on the SWRV data fetching state. ```vue ``` -------------------------------- ### useSWRV Hook Signature Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md The basic signature of the useSWRV hook. It must be called within a component's setup function or an active effect scope. ```typescript const { data, error, isValidating, isLoading, mutate } = useSWRV(key, fetcher, options) ``` -------------------------------- ### useSWRV - Core Data Fetching Composable Source: https://context7.com/kong/swrv/llms.txt The primary composable for fetching and caching remote data. It returns reactive refs for data, error, validation status, and a mutate function. It must be called within a component's `setup()` function or an active `effectScope()`. ```APIDOC ## useSWRV ### Description The primary composable for fetching and caching remote data. It returns reactive refs for `data`, `error`, `isValidating`, `isLoading`, and a `mutate` function. Must be called inside a component `setup()` function or an active `effectScope()`. ### Parameters - **key** (string | array | function | ref): Uniquely identifies a request. Passing `null`, `undefined`, or a function returning a falsy value disables fetching. - **fetcher** (function): An asynchronous function that fetches the data. - **options** (object, optional): Configuration options for SWRV. - **refreshInterval** (number): Poll interval in milliseconds. - **revalidateOnFocus** (boolean): Revalidate when window regains focus. - **dedupingInterval** (number): Dedupe requests interval in milliseconds. - **errorRetryCount** (number): Maximum number of retries on error. - **errorRetryInterval** (number): Interval between retries in milliseconds. ### Returns - **data**: Reactive ref containing the fetched data. - **error**: Reactive ref containing any error that occurred during fetching. - **isValidating**: Reactive ref indicating if a revalidation is in progress. - **isLoading**: Reactive ref indicating if the initial data is being loaded. - **mutate**: Function to manually trigger a revalidation. ### Example ```vue ``` ``` -------------------------------- ### Conditional Retry on Error Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md Example of configuring the `shouldRetryOnError` option to conditionally retry fetching based on the error message. This prevents retries for specific errors like 'Unauthorized'. ```typescript const { data, error } = useSWRV('/api/data', fetcher, { shouldRetryOnError: (err: Error): boolean => err.message !== 'Unauthorized' }) ``` -------------------------------- ### Using useSwrvState in a Vue Component Source: https://github.com/kong/swrv/blob/master/docs/features.md Integrate the `useSwrvState` composable into a Vue component to conditionally render UI elements based on the SWRV data fetching state. This example shows how to display errors, loading indicators, or the fetched data based on the detected state. ```vue ``` -------------------------------- ### Basic SWRV Usage with Vue Composition API Source: https://github.com/kong/swrv/blob/master/docs/guide.md Demonstrates how to use the useSWRV hook to fetch data. The hook accepts a unique key (e.g., API URL) and a fetcher function. It returns 'data' and 'error' refs that update reactively. ```vue ``` -------------------------------- ### Build Project Artifacts Source: https://github.com/kong/swrv/blob/master/CONTRIBUTING.md Builds the project's distributable artifacts, outputting to the esm/ and dist/ directories. This command is used during development to verify bundle output and before deployment. ```sh yarn build ``` -------------------------------- ### useSWRV Configuration Options Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md Details on the available configuration options for the useSWRV hook. ```APIDOC ## Configuration Options ### `refreshInterval` - **Type**: `number` - **Default**: `0` - **Description**: Polling interval in milliseconds. `0` disables polling. ### `dedupingInterval` - **Type**: `number` - **Default**: `2000` - **Description**: Time span in milliseconds to deduplicate requests with the same key. ### `ttl` - **Type**: `number` - **Default**: `0` - **Description**: Time to live in milliseconds for cached response data. `0` means data stays indefinitely. ### `shouldRetryOnError` - **Type**: `boolean | (err: Error) => boolean` - **Default**: `true` - **Description**: Determines if fetching should retry on error. Can be a boolean or a function that receives the error and returns a boolean. ### `errorRetryInterval` - **Type**: `number` - **Default**: `5000` - **Description**: Interval in milliseconds between error retries. ### `errorRetryCount` - **Type**: `number` - **Default**: `5` - **Description**: Maximum number of times to retry on error. ### `revalidateOnFocus` - **Type**: `boolean` - **Default**: `true` - **Description**: Auto-revalidates data when the window regains focus. ### `revalidateDebounce` - **Type**: `number` - **Default**: `0` - **Description**: Debounce time in milliseconds for revalidation. Useful for preventing unnecessary fetches when components unmount quickly. ### `cache` - **Type**: `object` - **Description**: A caching instance to store response data. See [src/lib/cache](src/lib/cache.ts) and the [Cache](/features#cache) section for more details. ``` -------------------------------- ### Dependent Fetching with Sequential Requests Source: https://context7.com/kong/swrv/llms.txt Demonstrates how to chain sequential data requests where one request depends on the result of a previous one. This is achieved by using a function key in `useSWRV` that references the data ref of the preceding request, ensuring the dependent request is deferred until its dependency resolves. ```vue ``` -------------------------------- ### Controlling Fetching with Keys Source: https://context7.com/kong/swrv/llms.txt Illustrates various ways to control when data fetching occurs using the `key` parameter in `useSWRV`. It covers string, array, function, and reactive ref keys, as well as how to disable fetching by returning `null` or `undefined`. ```vue ``` -------------------------------- ### Config options Source: https://context7.com/kong/swrv/llms.txt All configuration options can be set per `useSWRV` call. The `shouldRetryOnError` option accepts a function for fine-grained retry control. ```APIDOC ## Config options ### Description Global and per-call configuration options to customize SWRV's behavior, including polling, caching, focus revalidation, and error retry logic. ### Usage ```ts import useSWRV from 'swrv' // Per-call configuration overrides const { data, error } = useSWRV('/api/data', fetcher, { // Polling refreshInterval: 10000, // Re-fetch every 10 seconds; 0 = disabled // Caching ttl: 60000, // Cache entry expires after 60 seconds; 0 = forever dedupingInterval: 2000, // Suppress duplicate requests within 2 seconds // Focus revalidation revalidateOnFocus: true, // Re-fetch when user returns to the tab revalidateDebounce: 500, // Wait 500ms before revalidating on focus (reduces fetches during rapid navigation) // Error retry shouldRetryOnError: (err: Error) => { // Only retry on server errors, not on 4xx client errors return !err.message.includes('404') && !err.message.includes('401') }, errorRetryInterval: 3000, // Wait 3 seconds between retries errorRetryCount: 3, // Give up after 3 retries }) ``` ``` -------------------------------- ### useSWRV Core Data Fetching Source: https://context7.com/kong/swrv/llms.txt Demonstrates the primary `useSWRV` composable for fetching and caching remote data. It shows how to use reactive refs for data, error, validation states, and the mutate function. Configuration options like `refreshInterval`, `revalidateOnFocus`, and `errorRetryCount` are illustrated. ```vue ``` -------------------------------- ### Vuex Integration with SWRV (Vue 3) Source: https://github.com/kong/swrv/blob/master/README.md Demonstrates how to integrate SWRV with Vuex in a Vue 3 application. It shows how to use a watcher to update the Vuex store with changes from SWRV data. ```js import { defineComponent, ref, computed, watch } from 'vue' import { useStore } from 'vuex' import useSWRV from 'swrv' import { getAllTasks } from './api' export default defineComponent({ setup() { const store = useStore() const tasks = computed({ get: () => store.getters.allTasks, set: (tasks) => { store.dispatch('setTaskList', tasks) }, }) const addTasks = (newTasks) => store.dispatch('addTasks', { tasks: newTasks }) const { data } = useSWRV('tasks', getAllTasks) // Using a watcher, you can update the store with any changes coming from swrv watch(data, newTasks => { store.dispatch('addTasks', { source: 'Todoist', tasks: newTasks }) }) return { tasks } }, }) ``` -------------------------------- ### Configure `useSWRV` Options Source: https://context7.com/kong/swrv/llms.txt All configuration options can be set per `useSWRV` call. The `shouldRetryOnError` option accepts a function for fine-grained retry control. ```ts import useSWRV from 'swrv' // Per-call configuration overrides const { data, error } = useSWRV('/api/data', fetcher, { // Polling refreshInterval: 10000, // Re-fetch every 10 seconds; 0 = disabled // Caching ttl: 60000, // Cache entry expires after 60 seconds; 0 = forever dedupingInterval: 2000, // Suppress duplicate requests within 2 seconds // Focus revalidation revalidateOnFocus: true, // Re-fetch when user returns to the tab revalidateDebounce: 500, // Wait 500ms before revalidating on focus (reduces fetches during rapid navigation) // Error retry shouldRetryOnError: (err: Error) => { // Only retry on server errors, not on 4xx client errors return !err.message.includes('404') && !err.message.includes('401') }, errorRetryInterval: 3000, // Wait 3 seconds between retries errorRetryCount: 3, // Give up after 3 retries }) ``` -------------------------------- ### Run Project Tests Source: https://github.com/kong/swrv/blob/master/CONTRIBUTING.md Execute all unit tests for the Swrv project. The --watchAll flag enables watching for file changes and reruns tests, also entering Jest mode for filtering. ```sh yarn test ``` ```sh yarn test --watchAll ``` ```sh yarn test use-swrv ``` -------------------------------- ### Implement `LocalStorageCache` for Persistence Source: https://context7.com/kong/swrv/llms.txt Replace the default in-memory cache with a `localStorage`-backed adapter to persist data between page reloads and support offline usage in PWAs. ```ts import useSWRV from 'swrv' import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage' // Create a shared cache instance with a namespace key and optional TTL const lsCache = new LocalStorageCache('my-app-cache', 3600000) // 1 hour TTL // All useSWRV calls sharing this cache persist across sessions function useTodos() { const { data, error, mutate } = useSWRV('/api/todos', fetcher, { cache: lsCache, shouldRetryOnError: false, // Don't retry; serve stale data if offline revalidateOnFocus: true, }) return { data, error, mutate } } function useUserProfile(id: number) { const { data } = useSWRV( () => id && `/api/users/${id}`, fetcher, { cache: lsCache } ) return { data } } ``` -------------------------------- ### Key Parameter - Controlling Fetching Source: https://context7.com/kong/swrv/llms.txt The `key` parameter is crucial for identifying requests and controlling when fetching occurs. It supports various types, including functions for conditional fetching and reactive refs for dynamic updates. ```APIDOC ## Key Parameter ### Description The `key` parameter uniquely identifies a request. Passing `null`, `undefined`, or a function returning a falsy value disables fetching, enabling conditional and dependent data fetching patterns. ### Types - **String**: A simple string key for a request. - **Array**: An array of strings or other serializable values. The fetcher receives each element as an argument. - **Function**: A function that returns a string, array, `null`, or `undefined`. Fetching is only triggered if the function returns a truthy value. - **Ref**: A reactive reference. The request is re-fetched whenever the ref's value changes. ### Examples **String Key:** ```vue ``` **Array Key:** ```vue ``` **Function Key (Conditional Fetching):** ```vue ``` **Ref Key:** ```vue ``` **Disabling Fetching:** ```vue ``` ``` -------------------------------- ### `mutate` (instance) Source: https://context7.com/kong/swrv/llms.txt The `mutate` function returned by `useSWRV` forces a revalidation of the current key. You can pass updated data directly for optimistic UI updates, or call it without arguments to simply re-fetch. ```APIDOC ## `mutate` (instance) ### Description Forces a revalidation of the current key. Can be used for optimistic UI updates by passing updated data, or to simply re-fetch when called without arguments. ### Usage ```vue ``` ``` -------------------------------- ### Prefetch Data with SWRV Mutate Source: https://github.com/kong/swrv/blob/master/docs/features.md Use the `mutate` function to prefetch data and store it in the SWRV cache. This is useful for anticipating user actions, such as hovering over a link. The second parameter can be a Promise, and SWRV will use its resolved value. ```typescript import { mutate } from 'swrv' function prefetch() { mutate( '/api/data', fetch('/api/data').then((res) => res.json()) ) // the second parameter is a Promise // SWRV will use the result when it resolves } ``` -------------------------------- ### `LocalStorageCache` Source: https://context7.com/kong/swrv/llms.txt Replace the default in-memory cache with a `localStorage`-backed adapter to persist data between page reloads and support offline usage in PWAs. ```APIDOC ## `LocalStorageCache` ### Description Provides a persistent, offline-capable cache by using `localStorage`. This adapter allows data to persist across page reloads and enables offline usage. ### Usage ```ts import useSWRV from 'swrv' import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage' // Create a shared cache instance with a namespace key and optional TTL const lsCache = new LocalStorageCache('my-app-cache', 3600000) // 1 hour TTL // All useSWRV calls sharing this cache persist across sessions function useTodos() { const { data, error, mutate } = useSWRV('/api/todos', fetcher, { cache: lsCache, shouldRetryOnError: false, // Don't retry; serve stale data if offline revalidateOnFocus: true, }) return { data, error, mutate } } function useUserProfile(id: number) { const { data } = useSWRV( () => id && `/api/users/${id}`, fetcher, { cache: lsCache } ) return { data } } ``` ``` -------------------------------- ### Serve SWRV Data Only From Cache Source: https://github.com/kong/swrv/blob/master/docs/features.md This pattern shows how to configure a SWRV instance to only serve data from its cache without revalidating by setting the fetcher function to `null`. This is useful for components that rely on data already fetched by other instances. ```javascript // Component A const { data } = useSWRV('/api/config', fetcher) // Component B, only retrieve from cache const { data } = useSWRV('/api/config', null) ``` -------------------------------- ### Lint Project Code Source: https://github.com/kong/swrv/blob/master/CONTRIBUTING.md Run this command to automatically fix linting issues in the project. Use the --no-fix flag to only report issues without modifying files. ```sh yarn lint ``` ```sh yarn lint --no-fix ``` -------------------------------- ### useSwrvState Composable for UI State Management Source: https://context7.com/kong/swrv/llms.txt Map SWRV's reactive refs to explicit states (PENDING, VALIDATING, SUCCESS, ERROR, STALE_IF_ERROR) for state-machine-style UI rendering. This composable requires SWRV's data, error, and isValidating refs as input. ```typescript // composables/useSwrvState.ts import { ref, watchEffect, Ref } from 'vue' export const STATES = { PENDING: 'PENDING', VALIDATING: 'VALIDATING', SUCCESS: 'SUCCESS', ERROR: 'ERROR', STALE_IF_ERROR: 'STALE_IF_ERROR', } as const export type SwrvState = typeof STATES[keyof typeof STATES] export function useSwrvState( data: Ref, error: Ref, isValidating: Ref ) { const state = ref(STATES.PENDING) watchEffect(() => { if (data.value && isValidating.value) { state.value = STATES.VALIDATING; return } if (data.value && error.value) { state.value = STATES.STALE_IF_ERROR; return } if (data.value === undefined && !error.value) { state.value = STATES.PENDING; return } if (data.value && !error.value) { state.value = STATES.SUCCESS; return } if (data.value === undefined && error.value) { state.value = STATES.ERROR; return } }) return { state, STATES } } ``` ```vue ``` -------------------------------- ### useSWRV Hook Signature Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md The basic signature of the useSWRV hook, showing its parameters and return values. ```APIDOC ## useSWRV Hook ### Description Provides a hook for data fetching with caching and revalidation capabilities. ### Parameters - **key** (IKey) - Required - A unique identifier for the request. Can be a string, an array, null, undefined, or a reactive reference/getter. - **fetcher** (Function) - Optional - A Promise-returning function to fetch data. If null, fetches only from cache. If omitted, uses the fetch API. - **options** (IConfig) - Optional - Configuration options for the hook. ### Return Values - **data** (Ref) - The fetched data or undefined if not loaded. - **error** (Ref) - Any error thrown during fetching. - **isValidating** (Ref) - True when a request is ongoing. - **isLoading** (Ref) - True when a request is ongoing and data is not yet loaded. - **mutate** (Function) - Function to manually trigger revalidation or update cache. ``` -------------------------------- ### `mutate` (global) Source: https://context7.com/kong/swrv/llms.txt The exported `mutate` function updates the global SWRV cache for any key without requiring a component context. Useful for prefetching data or invalidating cache after mutations in a service layer. ```APIDOC ## `mutate` (global) ### Description Updates the global SWRV cache for any key without needing a component context. Ideal for prefetching or invalidating cache after external mutations. ### Usage ```ts import { mutate } from 'swrv' // Prefetch data before the component mounts (e.g., on hover) async function prefetchUser(id: number) { mutate( `/api/users/${id}`, fetch(`/api/users/${id}`).then(res => res.json()) // Second arg is a Promise — SWRV resolves and caches it ) } // Invalidate cache after a POST/PUT (all useSWRV instances with this key will re-fetch) async function createTodo(title: string) { await fetch('/api/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) }) // Wipe and re-fetch await mutate('/api/todos', fetch('/api/todos').then(r => r.json())) } // Set cache to a known value (no fetch triggered) mutate('/api/config', Promise.resolve({ theme: 'dark', locale: 'en' })) ``` ``` -------------------------------- ### Vue.js Redirect Script Source: https://github.com/kong/swrv/blob/master/docs/configuration.md This script uses Vue.js with VitePress to handle a page redirect. It sets up a countdown timer and navigates to a new route when the timer reaches zero. Ensure the script is placed within a Vue component context. ```javascript import { ref, onMounted, onUnmounted } from 'vue' import { useRouter } from 'vitepress' let timeout let seconds = ref(3) onMounted(() => { const router = useRouter() timeout = setInterval(() => { seconds.value-- if (seconds.value === 0) { clearInterval(timeout) router.go('/use-swrv') } }, 1000) }) onUnmounted(() => { clearInterval(timeout) }) ``` -------------------------------- ### Dependent Fetching Source: https://context7.com/kong/swrv/llms.txt Chains sequential requests by using a function key that depends on the data from a previous `useSWRV` call. The dependent request is automatically deferred until its dependency resolves. ```APIDOC ## Dependent Fetching ### Description Fetch data that depends on the result of a previous request by using a function key that reads from another `useSWRV` data ref. The dependent request is automatically deferred until its dependency resolves. ### Example ```vue ``` ``` -------------------------------- ### Update Global Cache with `mutate` (Global) Source: https://context7.com/kong/swrv/llms.txt The exported `mutate` function updates the global SWRV cache for any key without requiring a component context. Useful for prefetching data or invalidating cache after mutations. ```ts import { mutate } from 'swrv' // Prefetch data before the component mounts (e.g., on hover) async function prefetchUser(id: number) { mutate( `/api/users/${id}`, fetch(`/api/users/${id}`).then(res => res.json()) // Second arg is a Promise — SWRV resolves and caches it ) } // Invalidate cache after a POST/PUT (all useSWRV instances with this key will re-fetch) async function createTodo(title: string) { await fetch('/api/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) }) // Wipe and re-fetch await mutate('/api/todos', fetch('/api/todos').then(r => r.json())) } // Set cache to a known value (no fetch triggered) mutate('/api/config', Promise.resolve({ theme: 'dark', locale: 'en' })) ``` -------------------------------- ### Sync SWRV Data with Vuex Store Source: https://context7.com/kong/swrv/llms.txt Watch SWRV data and error refs to dispatch Vuex actions, synchronizing the cache with your centralized store. Ensure your Vuex store has modules for 'tasks' and 'notifications'. ```typescript import { defineComponent, watch } from 'vue' import { useStore } from 'vuex' import useSWRV from 'swrv' import { fetchAllTasks } from './api' export default defineComponent({ setup() { const store = useStore() const { data: tasks, error } = useSWRV('tasks', fetchAllTasks, { refreshInterval: 60000, }) // Mirror SWRV data into Vuex whenever it updates watch(tasks, (newTasks) => { if (newTasks) { store.dispatch('tasks/setAll', newTasks) } }) watch(error, (err) => { if (err) store.dispatch('notifications/add', { type: 'error', message: err.message }) }) // Vuex state is the source of truth for the template return { tasks: store.getters['tasks/all'], } }, }) ``` -------------------------------- ### Trigger Revalidation with `mutate` (Instance) Source: https://context7.com/kong/swrv/llms.txt Use the `mutate` function returned by `useSWRV` to force a revalidation of the current key. Pass updated data for optimistic UI updates or call without arguments to re-fetch. ```vue ``` -------------------------------- ### Cache-Only Mode with useSWRV Source: https://context7.com/kong/swrv/llms.txt Set the fetcher to `null` to read data solely from the cache without triggering network requests. This is useful for child components that consume data already fetched by a parent. ```vue ``` -------------------------------- ### Handle SWRV Errors with Vue Watchers Source: https://github.com/kong/swrv/blob/master/docs/features.md This snippet demonstrates how to use a watcher on the `error` ref returned by `useSWRV` to implement custom error handling logic. It logs the error message to the console. ```javascript export default { setup() { const { data, error } = useSWRV(key, fetch) function handleError(error) { console.error(error && error.message) } watch(error, handleError) return { data, error, } }, } ``` -------------------------------- ### IKey Type Definition Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md Defines the possible types for the 'key' parameter, which uniquely identifies a request. It can be a string, an array, null/undefined to disable fetching, or a reactive reference. ```typescript type IKey = | string | any[] | null | undefined | WatchSource ``` -------------------------------- ### Mutate Function Options Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md Type definitions for the options that can be passed to the mutate function for manual cache updates and revalidation. ```typescript type Data = | (() => Promise | any) | Promise | any interface RevalidateOptions { shouldRetryOnError?: boolean | ((err: Error) => boolean), errorRetryCount?: number } ``` -------------------------------- ### Fetcher Function Signature Source: https://github.com/kong/swrv/blob/master/docs/use-swrv.md The signature for the fetcher function. It should return data or a Promise resolving to data. If null, only cache is used. If omitted, the fetch API is used. ```typescript type Fetcher = (...args: any) => Data | Promise ```