Created
October 21, 2020 17:20
-
-
Save nandorojo/1da9a56c5f395ef086a988f4e373c62e to your computer and use it in GitHub Desktop.
No-cache policy with Vercel's SWR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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