-
Notifications
You must be signed in to change notification settings - Fork 0
/
default-queue-context.tsx
48 lines (39 loc) · 1.7 KB
/
default-queue-context.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { RunQueueOptions } from 'client-run-queue';
import { RunQueue } from 'client-run-queue';
import type { PropsWithChildren } from 'react';
import React, { useContext, useEffect, useMemo, useRef } from 'react';
import { useStableValue } from '../utility-hooks/use-stable-value';
const DefaultQueueContext = React.createContext<RunQueue>(new RunQueue('default'));
export const useDefaultQueue = () => useContext(DefaultQueueContext);
export interface DefaultQueueProviderProps extends RunQueueOptions {
/** A technical, but human-readable ID prefix, which isn't guaranteed to be unique. This will be suffixed by `':default'` */
idPrefix: string;
/**
* If `true`, `cancelAll` is called on the associated queue whenever this component is unmounted or whenever the idPrefix or other
* options change.
*
* @defaultValue `false`
*/
cancelAllOnUnmount?: boolean;
}
/** Provides a new default queue, which can be used in children using `useDefaultQueue` */
export const DefaultQueueProvider = ({
children,
idPrefix,
cancelAllOnUnmount = false,
...options
}: PropsWithChildren<DefaultQueueProviderProps>) => {
const stableOptions = useStableValue(options);
const queue = useMemo(() => new RunQueue(`${idPrefix}:default`, stableOptions), [idPrefix, stableOptions]);
const previousQueue = useRef<RunQueue>(queue);
useEffect(() => {
if (previousQueue.current !== queue) {
if (cancelAllOnUnmount) {
previousQueue.current?.cancelAll();
}
previousQueue.current = queue;
}
return cancelAllOnUnmount ? queue.cancelAll : undefined;
}, [cancelAllOnUnmount, queue]);
return <DefaultQueueContext.Provider value={queue}>{children}</DefaultQueueContext.Provider>;
};