Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

swrv

> 前端框架
Open source

Stale-while-revalidate data fetching for Vue

2.3K stars0 likes0 views
WebsiteGitHub

About

Stale-while-revalidate data fetching for Vue

swrv

[](https://www.npmjs.com/package/swrv)

swrv (pronounced "swerve") is a library using the Vue Composition API for remote data fetching. It is largely a port of swr.

  • Documentation

The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

Features:

  • Transport and protocol agnostic data fetching
  • Fast page navigation
  • Interval polling
  • SSR support (removed as of version 0.10.0 - read more)
  • Vue 3 Support
  • Revalidation on focus
  • Request deduplication
  • TypeScript ready
  • Minimal API
  • Stale-if-error
  • Customizable cache implementation
  • Error Retry

With swrv, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.

Table of Contents

  • Installation
    • Vue 3
    • Vue 2
  • Getting Started
  • Api
    • Parameters
    • Return Values
    • Config options
  • Prefetching
  • Dependent Fetching
  • Stale-if-error
  • State Management
    • useSwrvState
    • Vuex
  • Cache
    • localStorage
    • Serve from cache only
    • Per-app cache isolation
      • In test suites
    • Writing to a provided cache
  • Error Handling
  • FAQ
    • How is swrv different from the swr react library
    • Why does swrv make so many requests
    • How can I refetch swrv data to update it
  • Contributors ✨

Installation

Vue 3

bash
yarn add swrv

swrv supports every Vue 3 minor release since 3.2 (^3.2.0). Testing and bug reports track the latest patch of each minor.

Vue 2

Vue 2 reached end of life on 31 December 2023 and is no longer supported. The last releases to support it stay installable:

  • Vue 2.7 — [email protected], under the v2-latest tag
  • Vue 2.6 and below — [email protected], under the legacy tag. It uses the external @vue/composition-api plugin, set up as described in a previous version of the README.

Getting Started

xml
<template>
  

    

    

  </div>
</template>

<script>
import useSWRV from 'swrv'

export default {
  name: 'Profile',

  setup() {
    const { data, error } = useSWRV('/api/user', fetcher)

    return {
      data,
      error,
    }
  },
}
</script>

In this example, the Vue Hook useSWRV accepts a key and a fetcher function. key is a unique identifier of the request, normally the URL of the API. And the fetcher accepts key as its parameter and returns the data asynchronously.

useSWRV also returns 2 values: data and error. When the request (fetcher) is not yet finished, data will be undefined. And when we get a response, it sets data and error based on the result of fetcher and rerenders the component. This is because data and error are Vue Refs, and their values will be set by the fetcher response.

Note that fetcher can be any asynchronous function, so you can use your favorite data-fetching library to handle that part. When omitted, swrv falls back to the browser Fetch API.

Api

typescript
const { data, error, isValidating, mutate } = useSWRV(key, fetcher, options)

useSWRV must be called from a component setup() function or an active effectScope().

Parameters

Param Required Description
key yes a unique key string for the request (or a reactive reference / watcher function / null) (advanced usage)
fetcher a Promise returning function to fetch your data. If null, swrv will fetch from cache only and not revalidate. If omitted (i.e. undefined) then the fetch api will be used.
options an object of configuration options

Return Values

  • data: data for the given key resolved by fetcher (or undefined if not loaded)
  • error: error thrown by fetcher (or undefined)
  • isValidating: if there's a request or revalidation loading
  • mutate: function to trigger the validation manually

Config options

See Config Defaults

  • refreshInterval = 0 - polling interval in milliseconds. 0 means this is disabled.
  • dedupingInterval = 2000 - dedupe requests with the same key in this time span
  • ttl = 0 - time to live of response data in cache. 0 mean it stays around forever.
  • shouldRetryOnError = true - retry when fetcher has an error
  • errorRetryInterval = 5000 - error retry interval
  • errorRetryCount: 5 - max error retry count
  • revalidateOnFocus = true - auto revalidate when window gets focused
  • revalidateDebounce = 0 - debounce in milliseconds for revalidation. Useful for when a component is serving from the cache immediately, but then un-mounts soon thereafter (e.g. a user clicking "next" in pagination quickly) to avoid unnecessary fetches.
  • cache - caching instance to store response data in. See src/lib/cache, and Cache below.

Prefetching

Prefetching can be useful for when you anticipate user actions, like hovering over a link. SWRV exposes the mutate function so that results can be stored in the SWRV cache at a predetermined time.

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
}

Dependent Fetching

swrv also allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data fetch to happen.

…

Stale-if-error

One of the benefits of a stale content caching strategy is that the cache can be served when requests fail.swrv uses a stale-if-error strategy and will maintain data in the cache even if a useSWRV fetch returns an error.

xml
<template>
  

  

  <p v-if="data">
    hello {{ data.name }} of {{ data.birthplace }}. This content will continue
    to appear even if future requests to {{ endpoint }} fail!
  </p>
</template>

<script>
import { ref } from 'vue'
import useSWRV from 'swrv'

export default {
  name: 'Profile',

  setup() {
    const endpoint = ref('/api/user/Geralt')
    const { data, error } = useSWRV(endpoint.value, fetch)

    return {
      endpoint,
      data,
      error,
    }
  },
}
</script>

State Management

useSwrvState

Sometimes you might want to know the exact state where swrv is during stale-while-revalidate lifecyle. This is helpful when representing the UI as a function of state. Here is one way to detect state using a user-land composable useSwrvState function:

…

And then in your template you can use it like so:

…

Vuex

Most of the features of swrv handle the complex logic / ceremony that you'd have to implement yourself inside a vuex store. All swrv instances use the same global cache, so if you are using swrv alongside vuex, you can use global watchers on resolved swrv returned refs. It is encouraged to wrap useSWRV in a custom composable function so that you can do application level side effects if desired (e.g. dispatch a vuex action when data changes to log events or perform some logic).

Vue 3 example:

…

Cache

By default, a custom cache implementation is used to store fetcher response data cache, in-flight promise cache, and ref cache. Response data cache can be customized via the config.cache property. Built in cache adapters:

localStorage

A common usage case to have a better offline experience is to read from localStorage. Checkout the PWA example for more inspiration.

typescript
import useSWRV, { LocalStorageCache } from 'swrv'

function useTodos () {
  const { data, error } = useSWRV('/todos', undefined, {
    cache: new LocalStorageCache('swrv'),
    shouldRetryOnError: false
  })

  return {
    data,
    error
  }
}

Serve from cache only

To only retrieve a swrv cache response without revalidating, you can set the fetcher function to null from the useSWRV call. This can be useful when there is some higher level swrv composable that is always sending data to other instances, so you can assume that composables with a null fetcher will have data available. This isn't very intuitive, so will be looking for ways to improve this api in the future.

typescript
// Component A
const { data } = useSWRV('/api/config', fetcher)

// Component B, only retrieve from cache
const { data } = useSWRV('/api/config', null)

Per-app cache isolation

The response, in-flight promise, and ref caches are module singletons, shared by every useSWRV call in the process. That is what you want in an application, and what you do not want in a test suite: mounts share cache entries, so a later test can be served an entry left behind by an earlier one and its own fetcher never runs — silently, as stale data rather than an error.

provideSwrvCache gives an app its own set of caches. Every useSWRV call within that app's component tree uses them instead of the singletons; apps without a provide are unaffected.

typescript
import { provideSwrvCache } from 'swrv'

const app = createApp(App)
provideSwrvCache(app)

Pass overrides to swap in your own cache implementation for any of the three. Anything omitted gets a fresh instance.

typescript
const bundle = provideSwrvCache(app, { data: new LocalStorageCache('swrv') })

Calling it again on the same app is a no-op and returns the original bundle, so it is safe for a host app and a test harness to both call it. Passing overrides on that second call throws rather than discarding them — overrides replaces an implementation, so it only applies to the call that creates the bundle.

To seed entries into a bundle, or to inspect what was cached, reach for the bundle itself rather than overrides. getSwrvCache returns it for an app that h

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptswrvue

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架