Skip to content

Commit

Permalink
Merge pull request #2887 from reduxjs/bugfix/1.9-polyfills
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Nov 9, 2022
2 parents 69ee99a + cd7c208 commit 026221a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
29 changes: 21 additions & 8 deletions packages/toolkit/src/autoBatchEnhancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ export const prepareAutoBatched =
let promise: Promise<any>
const queueMicrotaskShim =
typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
? queueMicrotask.bind(
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: globalThis
)
: // reuse resolved promise, and allocate it lazily
(cb: () => void) =>
(promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>
Expand All @@ -23,18 +29,25 @@ const queueMicrotaskShim =
}, 0)
)

export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
| { type: 'raf' }
| { type: 'callback'; queueNotification: (notify: () => void) => void }

const createQueueWithTimer = (timeout: number) => {
return (notify: () => void) => {
setTimeout(notify, timeout)
}
}

// requestAnimationFrame won't exist in SSR environments.
// Fall back to a vague approximation just to keep from erroring.
const rAF =
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)

export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
| { type: 'raf' }
| { type: 'callback'; queueNotification: (notify: () => void) => void }

/**
* A Redux store enhancer that watches for "low-priority" actions, and delays
* notifying subscribers until either the queued callback executes or the
Expand Down Expand Up @@ -73,7 +86,7 @@ export const autoBatchEnhancer =
options.type === 'tick'
? queueMicrotaskShim
: options.type === 'raf'
? requestAnimationFrame
? rAF
: options.type === 'callback'
? options.queueNotification
: createQueueWithTimer(options.timeout)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import { createSlice, PayloadAction, AnyAction } from '@reduxjs/toolkit'
let promise: Promise<any>
const queueMicrotaskShim =
typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
? queueMicrotask.bind(
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: globalThis
)
: // reuse resolved promise, and allocate it lazily
(cb: () => void) =>
(promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>
Expand Down

0 comments on commit 026221a

Please sign in to comment.