MCPcopy Index your code
hub / github.com/Kong/swrv

github.com/Kong/swrv @v1.2.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.2.0 ↗ · + Follow
63 symbols 145 edges 25 files 2 documented · 3% 1 cross-repo links updated 15d agov1.2.0 · 2026-03-23★ 2,27825 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

swrv

npm build

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

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

The version of swrv you install depends on the Vue dependency in your project.

Vue 3

# Install the latest version
yarn add swrv

Vue 2.7

This version removes the dependency of the external @vue/composition-api plugin and adds vue to the peerDependencies, requiring a version that matches the following pattern: >= 2.7.0 < 3

# Install the 0.10.x version for Vue 2.7
yarn add swrv@v2-latest

Vue 2.6 and below

If you're installing for Vue 2.6.x and below, you may want to check out a previous version of the README to view how to initialize swrv utilizing the external @vue/composition-api plugin.

# Install the 0.9.x version for Vue < 2.7
yarn add swrv@legacy

Getting Started

<template>





failed to load




loading...




hello {{ data.name }}





</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

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.

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.

<template>


loading...




You have {{ projects.length }} projects


</template>

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

export default {
  name: 'Profile',

  setup() {
    const { data: user } = useSWRV('/api/user', fetch)
    const { data: projects } = useSWRV(() => user.value && '/api/projects?uid=' + user.value.id, fetch)
    // if the return value of the cache key function is falsy, the fetcher
    // will not trigger, but since `user` is inside the cache key function,
    // it is being watched so when it is available, then the projects will
    // be fetched.

    return {
      user,
      projects
    }
  },
}
</script>

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.

<template>


failed to load




loading...





    hello {{ data.name }} of {{ data.birthplace }}. This content will continue
    to appear even if future requests to {{ endpoint }} fail!



</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:

import { ref, watchEffect } from 'vue'

const STATES = {
  VALIDATING: 'VALIDATING',
  PENDING: 'PENDING',
  SUCCESS: 'SUCCESS',
  ERROR: 'ERROR',
  STALE_IF_ERROR: 'STALE_IF_ERROR',
}

export default function(data, error, isValidating) {
  const state = ref('idle')
  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) {
      state.value = STATES.ERROR
      return
    }
  })

  return {
    state,
    STATES,
  }
}

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

<template>






      {{ error }}





Loading...












      {{ data }}






</template>

<script>
import { computed } from 'vue'
import useSwrvState from '@/composables/useSwrvState'
import useSWRV from 'swrv'

export default {
  name: 'Repo',
  setup(props, { root }) {
    const page = computed(() => root.$route.params.id)
    const { data, error, isValidating } = useSWRV(
      () => `/api/${root.$route.params.id}`,
      fetcher
    )
    const { state, STATES } = useSwrvState(data, error, isValidating)

    return {
      state,
      STATES,
      data,
      error,
      page,
      isValidating,
    }
  },
}
</script>

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:

<script>
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
    }
  },
})
</script>

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.

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
  }
}

Serve from cache only

To only retrieve a swrv cache response without revalidating, you ca

Extension points exported contracts — how you extend this code

IConfig (Interface)
(no doc)
src/types.ts
ICacheItem (Interface)
(no doc)
src/cache/index.ts
revalidateOptions (Interface)
(no doc)
src/types.ts
IResponse (Interface)
(no doc)
src/types.ts

Core symbols most depended-on inside this repo

tick
called by 128
tests/utils/tick.ts
timeout
called by 103
tests/utils/jest-timeout.ts
useSWRV
called by 76
src/use-swrv.ts
get
called by 16
src/cache/index.ts
mutate
called by 12
src/use-swrv.ts
revalidate
called by 7
src/use-swrv.ts
serializeKey
called by 4
src/cache/index.ts
set
called by 4
src/cache/index.ts

Shape

Function 42
Method 13
Class 4
Interface 4

Languages

TypeScript100%

Modules by API surface

tests/use-swrv.spec.tsx14 symbols
src/use-swrv.ts10 symbols
src/cache/index.ts10 symbols
src/cache/adapters/localStorage.ts9 symbols
examples/pwa/src/registerServiceWorker.js7 symbols
tests/cache.spec.tsx3 symbols
src/types.ts3 symbols
src/lib/web-preset.ts3 symbols
tests/utils/tick.ts1 symbols
tests/utils/jest-timeout.ts1 symbols
src/lib/hash.ts1 symbols
examples/pwa/src/useTodos.js1 symbols

Used by 1 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add swrv \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page