Gathering detailed insights and metrics for swrv
Gathering detailed insights and metrics for swrv
Gathering detailed insights and metrics for swrv
Gathering detailed insights and metrics for swrv
npm install swrv
Typescript
Module System
Node Version
NPM Version
Add isLoading and update documentation
Updated on Jan 21, 2025
Capture error if exception is thrown when storing data to the cache
Updated on Jul 05, 2023
Remove unneeded await on setTimeout
Updated on Jan 12, 2023
Update devDependencies & add doc search
Updated on Dec 26, 2022
Prevent retry if component has been unmounted
Updated on Nov 02, 2022
Vue 3 Support
Updated on Oct 11, 2022
TypeScript (98%)
JavaScript (1.4%)
Shell (0.59%)
Total Downloads
29,813,466
Last Day
22,688
Last Week
406,014
Last Month
1,625,177
Last Year
23,558,679
Apache-2.0 License
2,226 Stars
221 Commits
75 Forks
38 Watchers
4 Branches
62 Contributors
Updated on May 09, 2025
Minified
Minified + Gzipped
Latest Version
1.1.0
Package Id
swrv@1.1.0
Unpacked Size
144.81 kB
Size
30.00 kB
File Count
52
NPM Version
8.11.0
Node Version
16.16.0
Published on
Jan 21, 2025
Cumulative downloads
Total Downloads
Last Day
11.6%
22,688
Compared to previous day
Last Week
12.4%
406,014
Compared to previous week
Last Month
-26.2%
1,625,177
Compared to previous month
Last Year
383.1%
23,558,679
Compared to previous year
1
29
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:
0.10.0
- read more)With swrv
, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
The version of swrv
you install depends on the Vue dependency in your project.
1# Install the latest version 2yarn add swrv
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
1# Install the 0.10.x version for Vue 2.7 2yarn add swrv@v2-latest
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.
1# Install the 0.9.x version for Vue < 2.7 2yarn add swrv@legacy
1<template> 2 <div> 3 <div v-if="error">failed to load</div> 4 <div v-if="!data">loading...</div> 5 <div v-else>hello {{ data.name }}</div> 6 </div> 7</template> 8 9<script> 10import useSWRV from 'swrv' 11 12export default { 13 name: 'Profile', 14 15 setup() { 16 const { data, error } = useSWRV('/api/user', fetcher) 17 18 return { 19 data, 20 error, 21 } 22 }, 23} 24</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.
1const { data, error, isValidating, mutate } = useSWRV(key, fetcher, options)
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 |
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 loadingmutate
: function to trigger the validation manuallySee Config Defaults
refreshInterval = 0
- polling interval in milliseconds. 0 means this is
disabled.dedupingInterval = 2000
- dedupe requests with the same key in this time
spanttl = 0
- time to live of response data in cache. 0 mean it stays around
forever.shouldRetryOnError = true
- retry when fetcher has an errorerrorRetryInterval = 5000
- error retry intervalerrorRetryCount: 5
- max error retry countrevalidateOnFocus = true
- auto revalidate when window gets focusedrevalidateDebounce = 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 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.
1import { mutate } from 'swrv' 2 3function prefetch() { 4 mutate( 5 '/api/data', 6 fetch('/api/data').then((res) => res.json()) 7 ) 8 // the second parameter is a Promise 9 // SWRV will use the result when it resolves 10}
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.
1<template> 2 <p v-if="!projects">loading...</p> 3 <p v-else>You have {{ projects.length }} projects</p> 4</template> 5 6<script> 7import { ref } from 'vue' 8import useSWRV from 'swrv' 9 10export default { 11 name: 'Profile', 12 13 setup() { 14 const { data: user } = useSWRV('/api/user', fetch) 15 const { data: projects } = useSWRV(() => user.value && '/api/projects?uid=' + user.value.id, fetch) 16 // if the return value of the cache key function is falsy, the fetcher 17 // will not trigger, but since `user` is inside the cache key function, 18 // it is being watched so when it is available, then the projects will 19 // be fetched. 20 21 return { 22 user, 23 projects 24 } 25 }, 26} 27</script>
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
.
1<template> 2 <div v-if="error">failed to load</div> 3 <div v-if="data === undefined && !error">loading...</div> 4 <p v-if="data"> 5 hello {{ data.name }} of {{ data.birthplace }}. This content will continue 6 to appear even if future requests to {{ endpoint }} fail! 7 </p> 8</template> 9 10<script> 11import { ref } from 'vue' 12import useSWRV from 'swrv' 13 14export default { 15 name: 'Profile', 16 17 setup() { 18 const endpoint = ref('/api/user/Geralt') 19 const { data, error } = useSWRV(endpoint.value, fetch) 20 21 return { 22 endpoint, 23 data, 24 error, 25 } 26 }, 27} 28</script>
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:
1import { ref, watchEffect } from 'vue' 2 3const STATES = { 4 VALIDATING: 'VALIDATING', 5 PENDING: 'PENDING', 6 SUCCESS: 'SUCCESS', 7 ERROR: 'ERROR', 8 STALE_IF_ERROR: 'STALE_IF_ERROR', 9} 10 11export default function(data, error, isValidating) { 12 const state = ref('idle') 13 watchEffect(() => { 14 if (data.value && isValidating.value) { 15 state.value = STATES.VALIDATING 16 return 17 } 18 if (data.value && error.value) { 19 state.value = STATES.STALE_IF_ERROR 20 return 21 } 22 if (data.value === undefined && !error.value) { 23 state.value = STATES.PENDING 24 return 25 } 26 if (data.value && !error.value) { 27 state.value = STATES.SUCCESS 28 return 29 } 30 if (data.value === undefined && error) { 31 state.value = STATES.ERROR 32 return 33 } 34 }) 35 36 return { 37 state, 38 STATES, 39 } 40}
And then in your template you can use it like so:
1<template> 2 <div> 3 <div v-if="[STATES.ERROR, STATES.STALE_IF_ERROR].includes(state)"> 4 {{ error }} 5 </div> 6 <div v-if="[STATES.PENDING].includes(state)">Loading...</div> 7 <div v-if="[STATES.VALIDATING].includes(state)"> 8 <!-- serve stale content without "loading" --> 9 </div> 10 <div 11 v-if=" 12 [STATES.SUCCESS, STATES.VALIDATING, STATES.STALE_IF_ERROR].includes( 13 state 14 ) 15 " 16 > 17 {{ data }} 18 </div> 19 </div> 20</template> 21 22<script> 23import { computed } from 'vue' 24import useSwrvState from '@/composables/useSwrvState' 25import useSWRV from 'swrv' 26 27export default { 28 name: 'Repo', 29 setup(props, { root }) { 30 const page = computed(() => root.$route.params.id) 31 const { data, error, isValidating } = useSWRV( 32 () => `/api/${root.$route.params.id}`, 33 fetcher 34 ) 35 const { state, STATES } = useSwrvState(data, error, isValidating) 36 37 return { 38 state, 39 STATES, 40 data, 41 error, 42 page, 43 isValidating, 44 } 45 }, 46} 47</script>
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:
1<script> 2import { defineComponent, ref, computed, watch } from 'vue' 3import { useStore } from 'vuex' 4import useSWRV from 'swrv' 5import { getAllTasks } from './api' 6 7export default defineComponent({ 8 setup() { 9 const store = useStore() 10 11 const tasks = computed({ 12 get: () => store.getters.allTasks, 13 set: (tasks) => { 14 store.dispatch('setTaskList', tasks) 15 }, 16 }) 17 18 const addTasks = (newTasks) => store.dispatch('addTasks', { tasks: newTasks }) 19 20 const { data } = useSWRV('tasks', getAllTasks) 21 22 // Using a watcher, you can update the store with any changes coming from swrv 23 watch(data, newTasks => { 24 store.dispatch('addTasks', { source: 'Todoist', tasks: newTasks }) 25 }) 26 27 return { 28 tasks 29 } 30 }, 31}) 32</script>
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:
A common usage case to have a better offline experience is to read from localStorage
. Checkout the PWA example for more inspiration.
1import useSWRV from 'swrv' 2import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage' 3 4function useTodos () { 5 const { data, error } = useSWRV('/todos', undefined, { 6 cache: new LocalStorageCache('swrv'), 7 shouldRetryOnError: false 8 }) 9 10 return { 11 data, 12 error 13 } 14}
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.
1// Component A
2const { data } = useSWRV('/api/config', fetcher)
3
4// Component B, only retrieve from cache
5const { data } = useSWRV('/api/config', null)
Since error
is returned as a Vue Ref, you can use watchers to handle any onError callback functionality. Check out the test.
1export default { 2 setup() { 3 const { data, error } = useSWRV(key, fetch) 4 5 function handleError(error) { 6 console.error(error && error.message) 7 } 8 9 watch(error, handleError) 10 11 return { 12 data, 13 error, 14 } 15 }, 16}
The swrv
library is meant to be used with the Vue Composition API (and eventually Vue 3) so it utilizes Vue's reactivity system to track dependencies and returns vue Ref
's as it's return values. This allows you to watch data
or build your own computed props. For example, the key function is implemented as Vue watch
er, so any changes to the dependencies in this function will trigger a revalidation in swrv
.
Features were built as needed for swrv
, and while the initial development of swrv
was mostly a port of swr, the feature sets are not 1-1, and are subject to diverge as they already have.
The idea behind stale-while-revalidate is that you always get fresh data eventually. You can disable some of the eager fetching such as config.revalidateOnFocus
, but it is preferred to serve a fast response from cache while also revalidating so users are always getting the most up to date data.
Swrv fetcher functions can be triggered on-demand by using the mutate
return value. This is useful when there is some event that needs to trigger a revalidation such a PATCH request that updates the initial GET request response data.
Thanks goes to these wonderful people (emoji key):
Darren Jennings 💻 📖 | Sébastien Chopin 💻 🤔 | Fernando Machuca 🎨 | ZEIT 🤔 | Adam DeHaven 💻 📖 🚧 |
This project follows the all-contributors specification. Contributions of any kind welcome!
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
all dependencies are pinned
Details
Reason
license file detected
Details
Reason
Found 5/22 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
1 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
103 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-05-05
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More