diff --git a/_internal/src/types.ts b/_internal/src/types.ts index e0215a7b5..3e2b9782b 100644 --- a/_internal/src/types.ts +++ b/_internal/src/types.ts @@ -72,6 +72,11 @@ export interface PublicConfiguration< * @defaultValue 5000 */ focusThrottleInterval: number + /** + * only revalidate once during a time span in milliseconds + * @defaultValue 5000 + */ + reconnectThrottleInterval: number /** * dedupe requests with the same key in this time span in milliseconds * @defaultValue 2000 @@ -116,6 +121,11 @@ export interface PublicConfiguration< * @link https://swr.vercel.app/docs/revalidation#disable-automatic-revalidations */ revalidateIfStale: boolean + /** + * ignore `dedupingInterval` (but not `reconnectThrottleInterval`) when revalidating after regaining a network connection + * @defaultValue false + */ + forceRevalidateOnReconnect: boolean /** * retry when fetcher has an error * @defaultValue true diff --git a/_internal/src/utils/config.ts b/_internal/src/utils/config.ts index a2eae1b3e..3a042b647 100644 --- a/_internal/src/utils/config.ts +++ b/_internal/src/utils/config.ts @@ -58,11 +58,13 @@ export const defaultConfig: FullConfiguration = mergeObjects( revalidateOnFocus: true, revalidateOnReconnect: true, revalidateIfStale: true, + forceRevalidateOnReconnect: false, shouldRetryOnError: true, // timeouts errorRetryInterval: slowConnection ? 10000 : 5000, focusThrottleInterval: 5 * 1000, + reconnectThrottleInterval: 5 * 1000, dedupingInterval: 2 * 1000, loadingTimeout: slowConnection ? 5000 : 3000, diff --git a/core/src/use-swr.ts b/core/src/use-swr.ts index 8480ea805..b7053d6e7 100644 --- a/core/src/use-swr.ts +++ b/core/src/use-swr.ts @@ -577,6 +577,7 @@ export const useSWRHandler = ( // Expose revalidators to global event listeners. So we can trigger // revalidation from the outside. let nextFocusRevalidatedAt = 0 + let nextReconnectRevalidatedAt = 0 const onRevalidate = ( type: RevalidateEvent, opts: { @@ -584,8 +585,8 @@ export const useSWRHandler = ( dedupe?: boolean } = {} ) => { + const now = Date.now() if (type == revalidateEvents.FOCUS_EVENT) { - const now = Date.now() if ( getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && @@ -595,8 +596,18 @@ export const useSWRHandler = ( softRevalidate() } } else if (type == revalidateEvents.RECONNECT_EVENT) { - if (getConfig().revalidateOnReconnect && isActive()) { - softRevalidate() + if ( + getConfig().revalidateOnReconnect && + now > nextReconnectRevalidatedAt && + isActive() + ) { + nextReconnectRevalidatedAt = now + getConfig().reconnectThrottleInterval + if (getConfig().forceRevalidateOnReconnect) { + return revalidate() + } + else { + softRevalidate() + } } } else if (type == revalidateEvents.MUTATE_EVENT) { return revalidate()