Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: revalidateIfStale has an effect on updates, not only mounting #1837

Merged
merged 1 commit into from
Feb 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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