swrv

repository·master·Indexed 22 days ago

https://github.com/kong/swrv

A Vue-based library for remote data fetching using the stale-while-revalidate (SWR) strategy. It provides reactive data updates, request deduplication, and automatic revalidation via the useSWRV hook. Supports Vue 3, Vue 2.7, and legacy Vue 2.6 versions, featuring a global cache, custom cache adapters like LocalStorageCache, and a stale-if-error strategy to maintain UI consistency during request failures.

Tokens
6.9K
Snippets
24
Records
40
Agent score
81%

What's inside swrv

  1. What is swrv and how does it work?

    master

    swrv (pronounced "swerve") is a library that provides Vue Composition API hooks for remote data fetching. It implements the Stale-While-Revalidate (SWR) strategy (RFC 5861).

    The SWR Lifecycle:

    1. Stale: The library first returns data from the cache if available.
    2. Revalidate: It then sends a fetch request to get fresh data.
    3. Update: Once the request completes, it updates the cache and the UI with the up-to-date data.

    This approach ensures fast page navigation and a highly reactive UI by providing a constant stream of data updates.

  2. Implement dependent fetching

    master

    SWRV supports fetching data that depends on previous results. To achieve this, pass a function as the cache key to useSWRV. If the function returns a falsy value, the fetcher will not trigger. Because the dependency is inside the cache key function, SWRV watches it and will trigger the fetch automatically once the dependency becomes available.

    <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>
  3. Implement dependent fetching with reactive keys

    master

    To fetch data that depends on the result of a previous request, pass a function as the key to useSWRV. This function can access reactive state. If the function returns a falsy value, the fetcher will not trigger. Once the dependency becomes available and the function returns a truthy key, swrv will automatically trigger the fetch.

    <script>
    import { ref } from 'vue'
    import useSWRV from 'swrv'
    
    export default {
      setup() {
        // First fetch: user data
        const { data: user } = useSWRV('/api/user', fetch)
    
        // Second fetch: depends on user.value.id
        // The key is a function that watches 'user'
        const { data: projects } = useSWRV(
          () => user.value && '/api/projects?uid=' + user.value.id, 
          fetch
        )
    
        return { user, projects }
      },
    }
    </script>
  4. How stale-if-error works

    master
    SWRV implements a stale-if-error strategy. This means that if a request fails, SWRV will maintain and continue to serve the existing data from the cache, even if the error ref is populated. This allows you to show stale content to the user instead of an empty error state.
  5. Understand the stale-if-error strategy

    master

    Because swrv uses a stale-while-revalidate strategy, it can serve cached data even if a new request fails. If a fetch returns an error, swrv will maintain the existing data in the cache, allowing the UI to continue displaying the last known good state instead of showing an error state immediately.

    <script>
    import { ref } from 'vue'
    import useSWRV from 'swrv'
    
    export default {
      setup() {
        const endpoint = ref('/api/user/Geralt')
        // If this fetch fails, 'data' will still contain the last successful response
        const { data, error } = useSWRV(endpoint.value, fetch)
    
        return { endpoint, data, error }
      },
    }
    </script>
  6. Track swrv lifecycle state with useSwrvState

    master

    To represent your UI as a function of the stale-while-revalidate lifecycle, you can implement a custom composable like useSwrvState. This allows you to distinguish between different states such as PENDING (initial load), VALIDATING (revalidating in background), SUCCESS, ERROR, and STALE_IF_ERROR (error occurred but stale data is available).

    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.value) {
          state.value = STATES.ERROR
          return
        }
      })
    
      return {
        state,
        STATES,
      }
    }
  7. Differences between swrv and SWR (React)

    master

    Vue and Reactivity

    swrv is designed for the Vue Composition API. It utilizes Vue's reactivity system and returns Vue Refs. The key function is implemented as a Vue watcher, meaning changes to its dependencies will automatically trigger a revalidation.

    Features

    While swrv is largely a port of the React swr library, the feature sets are not identical and may diverge over time.

  8. Run the Vite + Vue 3 example project

    master

    This example demonstrates how to use swrv within a project configured with Vite and Vue 3.

    To get the example running locally, follow these steps:

    1. Install dependencies: Use yarn to install the required packages.
    2. Start the development server: Run the application in development mode.
    yarn install
    yarn dev
  9. Integrate swrv with Vuex

    master

    Since all swrv instances share a global cache, you can synchronize swrv data with a Vuex store by using Vue watchers on the returned data ref. It is recommended to wrap useSWRV in a custom composable to manage application-level side effects, such as dispatching Vuex actions when data changes.

    <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>
  10. Install swrv

    master

    The installation command for swrv depends on your project's Vue version:

    Vue 3

    Install the latest version:

    yarn add swrv

    Vue 2.7

    Install the v2-latest version which supports Vue 2.7 (requires vue version >= 2.7.0 < 3):

    yarn add swrv@v2-latest

    Vue 2.6 and below

    Install the legacy version for older Vue versions:

    yarn add swrv@legacy