Vswr
🔥 Stale-While-Revalidate (SWR) strategy to fetch data in Vue 3
Install / Use
/learn @ConsoleTVs/VswrREADME

Table of Contents
- Introduction
- Features
- Upgrade guide
- Installation
- Getting Started
- Configuration options
- Global configuration options
- Dependent fetching
- Re-validate on demand
- Mutate on demand
- Parallel suspense
- Manual subscription
- Get values from the cache
- Error handling
- Clear Cache
- More Examples
Introduction
Quote from vercel's SWR for react:
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
With SWR, components will get a stream of data updates constantly and automatically. And the UI will be always fast and reactive.
Features
- :tada: Built for Vue 3
- :fire: Extremly small and well packed at 2.7kB (with polyfills!).
- Built-in cache and request deduplication.
- Dependent fetching of data that depends on other fetched data.
- Typescript friendly.
- Error handling by using the error variable provided.
- :fire: Efficient HTTP requests are only done when needed.
- Manual revalidation of the data by using
revalidate(). - Optimistic UI / Manual mutation of the data by using
mutate(). - Window focus revalidation of the data.
- Network change revalidation of the data.
- :fire: SSR / Initial data support for initial, offline data or SSR.
- Cache Invalidation when you need to invalidate all data or the specified keys (eg. a user logout).
- Offline support to be used without any revalidations with string keys.
- Global configuration available or per hook call.
- :fire: New in 2.0: Suspense Support to use with vue's
<Suspense>component.
New in 2.X.X
<Suspense>support withquerySuspenseError Boundaries:querySuspensethrows errors instead of using an error variable. You can use vue'sonErrorCaptureto create an error boundary.- Custom logic for network reconnect and app focus using the options
focusWhenandreconnectWhen. Usefull for environments outwise of the web (eg. Mobile or Desktop.
Upgrade Guide (1.X.X => 2.X.X)
Instance methods:
subscriberenamed tosubscribeDatauserenamed tosubscribegetOrWaitrenamed togetWaituseSWRrenamed toqueryqueryreturn propertystoprenamed tounsubscribe
Installation
npm i vswr
Getting Started
Without Suspense
<script setup>
import { query } from 'vswr'
// Call the `query` and pass the key you want to use. It will be pased
// to the fetcher function. The fetcher function can be configured globally
// or passed as one of the options to this function.
const { data: posts } = query('https://jsonplaceholder.typicode.com/posts')
</script>
<template>
<div v-if="posts">
<div v-for="post of posts" :key="post.id">
{{ post.title }}
</div>
</div>
</template>
With Suspense
<script setup>
import { querySuspense } from 'vswr'
// Call the `querySuspense` and pass the key you want to use. It will be pased
// to the fetcher function. The fetcher function can be configured globally
// or passed as one of the options to this function.
const { data: posts } = await querySuspense('https://jsonplaceholder.typicode.com/posts')
</script>
<template>
<div v-for="post of posts" :key="post.id">
{{ post.title }}
</div>
</template>
This is a simple example that will use SWR as the strategy to fetch the data. In this particular case, all the default options are used (or the ones specified in the global config) and it will fetch the data using the default or global fetcher and update the DOM when the request is done.
Configuration options
All hook calls can have their respective configuration options applied to it. Nevertheless you can also configure global options to avoid passing them to each hook call.
Signature
function query(key, options): SWRResponse
// Can be destructured to get the response as such:
const { data, error, mutate, revalidate, clear, unsubscribe, isLoading, isValid, promise } = query(key, options)
Parameters
-
key: A resolved or non-resolved key. Can either be a string, or a function. A function can be used for dependent fetching as seen below. -
options: An optional object with optional properties such as:fetcher: (key) => Promise<any> = (url) => fetch(url).then((res) => res.json()): Determines the fetcher function to use. This will be called to get the data.initialData: D = undefined: Represents the initial data to use instead of undefined. Keep in mind the component will still attempt to re-validate unlessrevalidateOnMountis set false.loadInitialCache: boolean = true: Determines if we should attempt to load the initial data from the cache in case initialData is undefined.revalidateOnStart: boolean = true: Determines if SWR should perform a revalidation when it's called.dedupingInterval: number = 2000: Determines the deduping interval. This interval represents the time SWR will avoid to perform a request if the last one was made beforededupingIntervalago.revalidateOnFocus: boolean = true: Revalidates the data when the window re-gains focus.focusThrottleInterval: number = 5000: Interval throttle for the focus event. This will ignore focus re-validation if it happened last timefocusThrottleIntervalago.focusWhen: (notify: () => void, options: VisibilityOptions) => void | (() => void): You can use this function to manually call the notify callback when the application has gained focus. You can also return a function that will be called as a cleanup.reconnectWhen: (notify: () => void, options: NetworkOptions) => void | (() => void): You can use this function to manually call the notify callback when the application has reconnected. You can also return a function that will be called as a cleanup.
Return Values (Without suspense)
data: Ref<D | undefined>: Stores the data of the HTTP response after the fetcher has proceesed it or undefined in case the HTTP request hasn't finished or there was an error.error: Ref<E | undefined>: Determines error of the HTTP response in case it happened or undefined if there was no error or the HTTP request is not completed yet.mutate: (value, options) => void: Mutate alias for the global mutate function without the need to append the key to it.revalidate: (options) => void: Revalidation alias for the global revalidate function without the need to append the key to it.clear: (options) => void: Clears the current key data from the cache.unsubscribe: () => void: Stops the execution of the watcher. This means the data will unsubscribe from the cache and error changes as well as all the event listeners.isLoading: ComputedRef<boolean>: Determines if the request is still on its way and therefore, it's still loading.isValid: ComputedRef<boolean>: Determines if the data is valid. This means that there is no error associated with the data. This exists because errors do not wipe the data value and can still be used.promise: Promise<D>: A promise that resolves to the data if the request is successful, and rejects the promise if an error is thrown. Keep in mind only the first case of those two cases will be registered, no further changes will be watched.
Return Values (With suspense)
data: Ref<D | undefined>: Stores the data of the HTTP response after the fetcher has proceesed it or undefined in case the HTTP request hasn't finished or there was an error.mutate: (value, options) => void: Mutate alias for the global mutate function without the need to append the key to it.revalidate: (options) => void: Revalidation alias for the global revalidate function without the need to append the key to it.clear: (options) => void: Clears the current key data from the cache.unsubscribe: () => void: Stops the execution of the watcher. This means the data will unsubscribe from the cache and error changes as well as all the event listeners.
Global configuration options
You can configure the options globally by creating a SWR instance and using it in your vue application. This step is not mandatory but it's recommened for most apps.
You can either choose to manually create a SWR instance and import it when needed or replace the default SWR instance used by all exported APIs. The second is recommended if only one instance will be needed for your application.
Signature
function createSWR(options): VSWR
function createDefaultSWR(options): VSWR
Parameters
options: SWROptions: Parameters of the options that will be passed to all components. They are the same as the ones on eachqueryfunction call.
Return value
A SWR instance that can be used to access all the API.
Example (with axios)
import { createApp } from 'vue'
import { createDefaultSWR } from 'vswr'
import App from './App.vue'
import axios from 'axios'
// Set the defaut SWR instance that will
// be used by all the exported APIs.
cr
