use stale swr and disable revalidation

This commit is contained in:
spencerwooo
2021-08-29 15:50:38 +01:00
parent b54d59cbba
commit 8a5f4482cd
5 changed files with 34 additions and 21 deletions
+25
View File
@@ -1,6 +1,31 @@
import useSWR, { cache, Key } from 'swr'
import axios from 'axios'
/**
* Extract the current web page's base url
* @returns base url of the page
*/
export const getBaseUrl = () => {
if (typeof window !== 'undefined') {
return window.location.origin
}
return ''
}
// Common axios fetch function
const fetcher = (url: string) => axios.get(url).then(res => res.data)
/**
* Use stale SWR instead of revalidating on each request. Not ideal for this scenario but have to do
* if fetching serverside props from component instead of pages.
* @param dataKey request url
* @returns useSWR instance
*/
export const useStaleSWR = (dataKey: Key) => {
const revalidationOptions = {
revalidateOnMount: !cache.has(dataKey), //here we refer to the SWR cache
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
return useSWR(dataKey, fetcher, revalidationOptions)
}