Skip to content

Commit

Permalink
refactor: revalidateIfStale has an effect on updates, not only mounti…
Browse files Browse the repository at this point in the history
…ng (#1837)
  • Loading branch information
koba04 committed Feb 6, 2022
1 parent c63cafc commit 01e0594
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,15 @@ export const useSWRHandler = <Data = any, Error = any>(
const info = cache.get(keyInfo) || {}
const error = info.error

const isInitialMount = !initialMountedRef.current

// - Suspense mode and there's stale data for the initial render.
// - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.
// - `revalidateIfStale` is enabled but `data` is not defined.
const shouldRevalidateOnMount = () => {
const shouldRevalidate = () => {
// If `revalidateOnMount` is set, we take the value directly.
if (!isUndefined(revalidateOnMount)) return revalidateOnMount
if (isInitialMount && !isUndefined(revalidateOnMount))
return revalidateOnMount

// If it's paused, we skip revalidation.
if (getConfig().isPaused()) return false
Expand All @@ -109,7 +112,7 @@ export const useSWRHandler = <Data = any, Error = any>(
if (info.isValidating) return true

// If it's not mounted yet and it should revalidate on mount, revalidate.
return !initialMountedRef.current && shouldRevalidateOnMount()
return isInitialMount && shouldRevalidate()
}
const isValidating = resolveValidating()

Expand Down Expand Up @@ -372,8 +375,7 @@ export const useSWRHandler = <Data = any, Error = any>(
useIsomorphicLayoutEffect(() => {
if (!key) return

// Not the initial render.
const keyChanged = initialMountedRef.current
const keyChanged = key !== keyRef.current
const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE)

// Expose state updater to global event listeners. So we can update hook's
Expand Down Expand Up @@ -443,7 +445,7 @@ export const useSWRHandler = <Data = any, Error = any>(
}

// Trigger a revalidation.
if (shouldRevalidateOnMount()) {
if (shouldRevalidate()) {
if (isUndefined(data) || IS_SERVER) {
// Revalidate immediately.
softRevalidate()
Expand Down

0 comments on commit 01e0594

Please sign in to comment.