SWRV Documentation

website·Indexed 30 days ago

https://docs-swrv.netlify.app/

A feature-rich, transport and protocol agnostic data fetching library providing revalidation on focus, polling, in-flight de-duplication, and prefetching via the useSWRV hook.

Tokens
3.1K
Snippets
19
Records
23
Agent score
75%

What's inside SWRV

  1. Overview of SWR data fetching features

    SWR provides a transport and protocol agnostic approach to data fetching. Key features include:

    • Revalidation on focus: Automatically refreshes data when the window regains focus.
    • Polling: Supports periodic automatic data refreshing.
    • In-flight de-duplication: Prevents multiple identical requests from being sent simultaneously, reducing network load.
  2. Overview of swrv data fetching

    swrv is a Vue Composition API library for remote data fetching, based on the 'stale-while-revalidate' (SWR) strategy. It returns cached (stale) data first, sends a fetch request to revalidate, and then updates with the latest data. Key features include transport-agnostic fetching, interval polling, revalidation on focus, request deduplication, and TypeScript support. Note: SSR support was removed as of version 0.10.0.
  3. Seed or inspect the SWRV cache bundle

    To seed entries into a bundle or inspect cached data, use the getSwrvCache function. This returns the cache bundle for the application, allowing direct manipulation of the data cache via the .set() method.
    import { getSwrvCache } from 'swrv'
    
    // Seed the cache with a user object for the '/api/user' key
    getSwrvCache(app)?.data.set('/api/user', { data: user }, 0)
  4. Manually integrate SWRV cache plugin in tests

    If you are using a custom mount helper or a test runner that does not use @vue/test-utils, you can manually provide the cache by adding the swrvCachePlugin to the Vue global plugins. Use swrvCachePlugin instead of { install: provideSwrvCache } to avoid plugin options being incorrectly passed into the overrides parameter.
    import { swrvCachePlugin } from 'swrv'
    
    mount(Component, { global: { plugins: [swrvCachePlugin] } })
  5. Handle SWRV errors using watchers

    Since the error returned by useSWRV is a Vue Ref, you can use a watch to implement onError callback functionality.
    setup() {
      const { data, error } = useSWRV(key, fetch)
    
      watch(error, (err) => {
        if (err) console.error(err.message)
      })
    
      return { data, error }
    }
  6. Integrate SWRV with Vuex

    SWRV uses a global cache. To sync SWRV data with a Vuex store, use a Vue watch on the data ref returned by useSWRV to dispatch actions to the store whenever the cache updates.
    <script>
    import { defineComponent, watch, computed } from 'vue'
    import { useStore } from 'vuex'
    import useSWRV from 'swrv'
    
    export default defineComponent({
      setup() {
        const store = useStore()
        const { data } = useSWRV('tasks', getAllTasks)
    
        watch(data, newTasks => {
          store.dispatch('addTasks', { source: 'SWRV', tasks: newTasks })
        })
    
        return { tasks: computed(() => store.getters.allTasks) }
      },
    })
    </script>
  7. Fetch data using the useSWRV hook

    useSWRV is a hook for data fetching that must be called from a component setup() function or an active effectScope(). It takes a unique key, a fetcher function, and an optional configuration object.
    const { data, error, isValidating, isLoading, mutate } = useSWRV(key, fetcher, options)
  8. Prefetch data using the mutate function

    SWRV provides a mutate function that allows you to manually populate the cache at a predetermined time (e.g., when a user hovers over a link) to improve perceived performance.
    import { mutate } from 'swrv'
    
    function prefetch() {
      mutate(
        '/api/data',
        fetch('/api/data').then((res) => res.json())
      )
      // The second parameter is a Promise; SWRV uses the result when it resolves
    }
  9. Install swrv for legacy Vue 2 versions

    Vue 2 is no longer officially supported, but legacy versions of swrv are available:

    • For Vue 2.7: Use swrv@0.10.0 (available under the v2-latest tag).
    • For Vue 2.6 and below: Use swrv@0.9.6 (available under the legacy tag). This version requires the @vue/composition-api plugin.
  10. Configure SWRV for test suites with Vitest or Jest

    To ensure every component mounted via @vue/test-utils receives its own isolated cache, add the swrv/testing setup module to your test runner. This removes the need for per-test or per-mount wiring. Note that @vue/test-utils is an optional peer dependency required for this functionality.
    // vitest.config.ts
    export default defineConfig({
      test: {
        setupFiles: ['swrv/testing'],
      },
    })
    // jest.config.js
    module.exports = {
      setupFilesAfterEnv: ['swrv/testing'],
    }
  11. Mutate a provided cache within Vue setup

    The standalone mutate function writes to module singletons by default because it is often called in event handlers where Vue's inject is unavailable. To mutate a specific provided cache, inject the bundle using swrvCacheInjectionKey within the setup function and pass the cache's data and refs to the mutate call.
    setup () {
      const cache = inject(swrvCacheInjectionKey)
      const save = () => mutate('/api/user', next, cache?.data, 0, cache?.refs)
    
      return { save }
    }