swrv

Stale-while-revalidate data fetching for Vue

README

swrv

undefined 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


  - Vue 3
  - Vue 2.7
- Api
  - Vuex
- FAQ

Installation


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

Vue 3


  1. ``` sh
  2. # Install the latest version
  3. yarn add swrv
  4. ```

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

  1. ``` sh
  2. # Install the 0.10.x version for Vue 2.7
  3. yarn add swrv@v2-latest
  4. ```

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 initializeswrv utilizing the external @vue/composition-api plugin.

  1. ``` sh
  2. # Install the 0.9.x version for Vue < 2.7
  3. yarn add swrv@legacy
  4. ```

Getting Started


  1. ```vue
  2. <template>
  3.   <div>
  4.     <div v-if="error">failed to load</div>
  5.     <div v-if="!data">loading...</div>
  6.     <div v-else>hello {{ data.name }}</div>
  7.   </div>
  8. </template>
  9. <script>
  10. import useSWRV from 'swrv'

  11. export default {
  12.   name: 'Profile',

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

  15.     return {
  16.       data,
  17.       error,
  18.     }
  19.   },
  20. }
  21. </script>
  22. ```

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


  1. ```ts
  2. const { data, error, isValidating, mutate } = useSWRV(key, fetcher, options)
  3. ```

Parameters


ParamRequiredDescription
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`key`yesa
`fetcher`|
`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



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

  1. ```ts
  2. import { mutate } from 'swrv'

  3. function 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. }
  11. ```

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.

  1. ```vue
  2. <template>
  3.   <p v-if="!projects">loading...</p>
  4.   <p v-else>You have {{ projects.length }} projects</p>
  5. </template>
  6. <script>
  7. import { ref } from 'vue'
  8. import useSWRV from 'swrv'

  9. export default {
  10.   name: 'Profile',

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

  18.     return {
  19.       user,
  20.       projects
  21.     }
  22.   },
  23. }
  24. </script>
  25. ```

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 maintaindata in the cache even if a useSWRV fetch returns an error.

  1. ```vue
  2. <template>
  3.   <div v-if="error">failed to load</div>
  4.   <div v-if="data === undefined && !error">loading...</div>
  5.   <p v-if="data">
  6.     hello {{ data.name }} of {{ data.birthplace }}. This content will continue
  7.     to appear even if future requests to {{ endpoint }} fail!
  8.   </p>
  9. </template>
  10. <script>
  11. import { ref } from 'vue'
  12. import useSWRV from 'swrv'

  13. export default {
  14.   name: 'Profile',

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

  18.     return {
  19.       endpoint,
  20.       data,
  21.       error,
  22.     }
  23.   },
  24. }
  25. </script>
  26. ```

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:

  1. ``` js
  2. import { ref, watchEffect } from 'vue'

  3. const STATES = {
  4.   VALIDATING: 'VALIDATING',
  5.   PENDING: 'PENDING',
  6.   SUCCESS: 'SUCCESS',
  7.   ERROR: 'ERROR',
  8.   STALE_IF_ERROR: 'STALE_IF_ERROR',
  9. }

  10. export default function(data, error, isValidating) {
  11.   const state = ref('idle')
  12.   watchEffect(() => {
  13.     if (data.value && isValidating.value) {
  14.       state.value = STATES.VALIDATING
  15.       return
  16.     }
  17.     if (data.value && error.value) {
  18.       state.value = STATES.STALE_IF_ERROR
  19.       return
  20.     }
  21.     if (data.value === undefined && !error.value) {
  22.       state.value = STATES.PENDING
  23.       return
  24.     }
  25.     if (data.value && !error.value) {
  26.       state.value = STATES.SUCCESS
  27.       return
  28.     }
  29.     if (data.value === undefined && error) {
  30.       state.value = STATES.ERROR
  31.       return
  32.     }
  33.   })

  34.   return {
  35.     state,
  36.     STATES,
  37.   }
  38. }
  39. ```

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

  1. ```vue
  2. <template>
  3.   <div>
  4.     <div v-if="[STATES.ERROR, STATES.STALE_IF_ERROR].includes(state)">
  5.       {{ error }}
  6.     </div>
  7.     <div v-if="[STATES.PENDING].includes(state)">Loading...</div>
  8.     <div v-if="[STATES.VALIDATING].includes(state)">
  9.       
  10.     </div>
  11.     <div
  12.       v-if="
  13.         [STATES.SUCCESS, STATES.VALIDATING, STATES.STALE_IF_ERROR].includes(
  14.           state
  15.         )
  16.       "
  17.     >
  18.       {{ data }}
  19.     </div>
  20.   </div>
  21. </template>
  22. <script>
  23. import { computed } from 'vue'
  24. import useSwrvState from '@/composables/useSwrvState'
  25. import useSWRV from 'swrv'

  26. export default {
  27.   name: 'Repo',
  28.   setup(props, { root }) {
  29.     const page = computed(() => root.$route.params.id)
  30.     const { data, error, isValidating } = useSWRV(
  31.       () => `/api/${root.$route.params.id}`,
  32.       fetcher
  33.     )
  34.     const { state, STATES } = useSwrvState(data, error, isValidating)

  35.     return {
  36.       state,
  37.       STATES,
  38.       data,
  39.       error,
  40.       page,
  41.       isValidating,
  42.     }
  43.   },
  44. }
  45. </script>
  46. ```

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:

  1. ```vue
  2. <script>
  3. import { defineComponent, ref, computed, watch } from 'vue'
  4. import { useStore } from 'vuex'
  5. import useSWRV from 'swrv'
  6. import { getAllTasks } from './api'

  7. export default defineComponent({
  8.   setup() {
  9.     const store = useStore()

  10.     const tasks = computed({
  11.       get: () => store.getters.allTasks,
  12.       set: (tasks) => {
  13.         store.dispatch('setTaskList', tasks)
  14.       },
  15.     })

  16.     const addTasks = (newTasks) => store.dispatch('addTasks', { tasks: newTasks })

  17.     const { data } = useSWRV('tasks', getAllTasks)

  18.     // Using a watcher, you can update the store with any changes coming from swrv
  19.     watch(data, newTasks => {
  20.       store.dispatch('addTasks', { source: 'Todoist', tasks: newTasks })
  21.     })

  22.     return {
  23.       tasks
  24.     }
  25.   },
  26. })
  27. </script>
  28. ```

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.

  1. ```ts
  2. import useSWRV from 'swrv'
  3. import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage'

  4. function useTodos () {
  5.   const { data, error } = useSWRV('/todos', undefined, {
  6.     cache: new LocalStorageCache('swrv'),
  7.     shouldRetryOnError: false
  8.   })

  9.   return {
  10.     data,
  11.     error
  12.   }
  13. }
  14. ```

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.

  1. ```ts
  2. // Component A
  3. const { data } = useSWRV('/api/config', fetcher)

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

Error Handling


Since error is returned as a Vue Ref, you can use watchers to handle any onError callback functionality. Check out the test.

  1. ```ts
  2. export default {
  3.   setup() {
  4.     const { data, error } = useSWRV(key, fetch)

  5.     function handleError(error) {
  6.       console.error(error && error.message)
  7.     }

  8.     watch(error, handleError)

  9.     return {
  10.       data,
  11.       error,
  12.     }
  13.   },
  14. }
  15. ```

FAQ


How is swrv different from the swr react library


Vue and Reactivity


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 watcher, so any changes to the dependencies in this function will trigger a revalidation in swrv.

Features


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.

Why does swrv make so many requests


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.

How can I refetch swrv data to update it


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.

Contributors ✨


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!