Skip to content

Commit cd7c208

Browse files
committed
Fall back to setTimeout polyfill for rAF in SSR scenarios
1 parent 1cb135e commit cd7c208

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

packages/toolkit/src/autoBatchEnhancer.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,25 @@ const queueMicrotaskShim =
2929
}, 0)
3030
)
3131

32-
export type AutoBatchOptions =
33-
| { type: 'tick' }
34-
| { type: 'timer'; timeout: number }
35-
| { type: 'raf' }
36-
| { type: 'callback'; queueNotification: (notify: () => void) => void }
37-
3832
const createQueueWithTimer = (timeout: number) => {
3933
return (notify: () => void) => {
4034
setTimeout(notify, timeout)
4135
}
4236
}
4337

38+
// requestAnimationFrame won't exist in SSR environments.
39+
// Fall back to a vague approximation just to keep from erroring.
40+
const rAF =
41+
typeof window !== 'undefined' && window.requestAnimationFrame
42+
? window.requestAnimationFrame
43+
: createQueueWithTimer(10)
44+
45+
export type AutoBatchOptions =
46+
| { type: 'tick' }
47+
| { type: 'timer'; timeout: number }
48+
| { type: 'raf' }
49+
| { type: 'callback'; queueNotification: (notify: () => void) => void }
50+
4451
/**
4552
* A Redux store enhancer that watches for "low-priority" actions, and delays
4653
* notifying subscribers until either the queued callback executes or the
@@ -79,7 +86,7 @@ export const autoBatchEnhancer =
7986
options.type === 'tick'
8087
? queueMicrotaskShim
8188
: options.type === 'raf'
82-
? requestAnimationFrame
89+
? rAF
8390
: options.type === 'callback'
8491
? options.queueNotification
8592
: createQueueWithTimer(options.timeout)

0 commit comments

Comments
 (0)