Skip to content

Instantly share code, notes, and snippets.

@nandorojo
Created October 21, 2020 17:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nandorojo/1da9a56c5f395ef086a988f4e373c62e to your computer and use it in GitHub Desktop.
Save nandorojo/1da9a56c5f395ef086a988f4e373c62e to your computer and use it in GitHub Desktop.
No-cache policy with Vercel's SWR
import useNativeSWR from 'swr'
import { useRef } from 'react'
// inspired by https://github.com/vercel/swr/discussions/456
export default function useSWR(key, fetcher, options = {}) {
const { cachePolicy, ...opts } = options
const random = useRef(new Date())
return useNativeSWR(
() => {
const shouldAvoidCache = cachePolicy === 'no-cache'
if (!shouldAvoidCache) {
return typeof key === 'function' ? key() : key
}
let finalKey = key
if (typeof key === 'function') finalKey = key()
if (!Array.isArray(finalKey)) finalKey = [finalKey]
return [...finalKey, random]
},
fetcher,
opts
)
}
// usage:
const fetcher = () => getUsers()
const { data } = useSWR('users', fetcher, { cachePolicy: 'no-cache' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment