@hyper-fetch/react 6.0.1 → 7.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.json +8 -3
- package/README.md +5 -5
- package/dist/index.d.ts +167 -166
- package/dist/{index.esm.js → index.js} +462 -431
- package/dist/index.js.map +7 -0
- package/package.json +12 -13
- package/src/helpers/use-request-events/use-request-events.hooks.ts +79 -80
- package/src/helpers/use-request-events/use-request-events.types.ts +24 -22
- package/src/helpers/use-socket-state/use-socket-state.constants.ts +4 -1
- package/src/helpers/use-socket-state/use-socket-state.hooks.ts +39 -29
- package/src/helpers/use-socket-state/use-socket-state.types.ts +4 -1
- package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +4 -3
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +82 -115
- package/src/helpers/use-tracked-state/use-tracked-state.types.ts +42 -25
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +45 -41
- package/src/hooks/use-app-manager/use-app-manager.hooks.ts +2 -2
- package/src/hooks/use-cache/use-cache.constants.ts +1 -1
- package/src/hooks/use-cache/use-cache.hooks.ts +32 -27
- package/src/hooks/use-cache/use-cache.types.ts +4 -22
- package/src/hooks/use-emitter/use-emitter.hooks.ts +50 -18
- package/src/hooks/use-fetch/use-fetch.constants.ts +6 -5
- package/src/hooks/use-fetch/use-fetch.hooks.ts +71 -79
- package/src/hooks/use-fetch/use-fetch.types.ts +28 -9
- package/src/hooks/use-listener/use-listener.hooks.ts +15 -21
- package/src/hooks/use-queue/use-queue.constants.ts +2 -1
- package/src/hooks/use-queue/use-queue.hooks.ts +123 -42
- package/src/hooks/use-queue/use-queue.types.ts +14 -5
- package/src/hooks/use-submit/use-submit.constants.ts +3 -3
- package/src/hooks/use-submit/use-submit.hooks.ts +39 -53
- package/src/hooks/use-submit/use-submit.types.ts +5 -6
- package/src/index.ts +1 -3
- package/src/provider/index.ts +2 -0
- package/src/{config-provider/config-provider.tsx → provider/provider.tsx} +8 -5
- package/src/{config-provider/config-provider.types.ts → provider/provider.types.ts} +15 -8
- package/src/utils/deep-equal.utils.ts +1 -3
- package/tsconfig.json +2 -2
- package/dist/index.cjs.js +0 -1550
- package/dist/index.cjs.js.map +0 -7
- package/dist/index.esm.js.map +0 -7
- package/src/config-provider/index.ts +0 -2
- package/src/hooks/use-event-messages/index.ts +0 -2
- package/src/hooks/use-event-messages/use-event-messages.hooks.ts +0 -69
- package/src/hooks/use-event-messages/use-event-messages.types.ts +0 -4
- package/src/types/index.ts +0 -1
- package/src/types/invalidation.types.ts +0 -3
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
import { useRef } from "react";
|
|
2
1
|
import { useDidUpdate, useDidMount, useWillUnmount } from "@better-hooks/lifecycle";
|
|
3
2
|
import { useDebounce, useThrottle } from "@better-hooks/performance";
|
|
4
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
RequestInstance,
|
|
5
|
+
ExtractAdapterStatusType,
|
|
6
|
+
ExtractAdapterType,
|
|
7
|
+
ExtractAdapterExtraType,
|
|
8
|
+
} from "@hyper-fetch/core";
|
|
9
|
+
import { useRef } from "react";
|
|
5
10
|
|
|
6
11
|
import { useRequestEvents, useTrackedState } from "helpers";
|
|
7
|
-
import { UseFetchOptionsType, useFetchDefaultOptions, UseFetchReturnType } from "hooks/use-fetch";
|
|
8
|
-
import {
|
|
12
|
+
import { UseFetchOptionsType, useFetchDefaultOptions, UseFetchReturnType, UseFetchRequest } from "hooks/use-fetch";
|
|
13
|
+
import { useProvider } from "provider";
|
|
9
14
|
import { getBounceData } from "utils";
|
|
10
|
-
import { InvalidationKeyType } from "types";
|
|
11
15
|
|
|
12
16
|
/**
|
|
13
17
|
* This hooks aims to retrieve data from server.
|
|
@@ -15,32 +19,29 @@ import { InvalidationKeyType } from "types";
|
|
|
15
19
|
* @param options Hook options
|
|
16
20
|
* @returns
|
|
17
21
|
*/
|
|
18
|
-
export const useFetch = <
|
|
19
|
-
request:
|
|
20
|
-
options
|
|
21
|
-
): UseFetchReturnType<
|
|
22
|
+
export const useFetch = <R extends RequestInstance>(
|
|
23
|
+
request: R extends UseFetchRequest<R> ? R : UseFetchRequest<R>,
|
|
24
|
+
options?: UseFetchOptionsType<R>,
|
|
25
|
+
): UseFetchReturnType<R> => {
|
|
22
26
|
// Build the configuration options
|
|
23
|
-
const
|
|
27
|
+
const { config: globalConfig } = useProvider();
|
|
24
28
|
const {
|
|
25
|
-
dependencies
|
|
26
|
-
disabled
|
|
27
|
-
dependencyTracking
|
|
28
|
-
revalidate
|
|
29
|
-
|
|
30
|
-
refresh
|
|
31
|
-
refreshTime
|
|
32
|
-
refetchBlurred
|
|
33
|
-
refetchOnBlur
|
|
34
|
-
refetchOnFocus
|
|
35
|
-
refetchOnReconnect
|
|
36
|
-
bounce
|
|
37
|
-
bounceType
|
|
38
|
-
bounceTime
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
// @ts-ignore
|
|
42
|
-
bounceTimeout = useFetchDefaultOptions.bounceTime,
|
|
43
|
-
deepCompare = useFetchDefaultOptions.deepCompare,
|
|
29
|
+
dependencies,
|
|
30
|
+
disabled,
|
|
31
|
+
dependencyTracking,
|
|
32
|
+
revalidate,
|
|
33
|
+
initialResponse,
|
|
34
|
+
refresh,
|
|
35
|
+
refreshTime,
|
|
36
|
+
refetchBlurred,
|
|
37
|
+
refetchOnBlur,
|
|
38
|
+
refetchOnFocus,
|
|
39
|
+
refetchOnReconnect,
|
|
40
|
+
bounce,
|
|
41
|
+
bounceType,
|
|
42
|
+
bounceTime,
|
|
43
|
+
bounceTimeout,
|
|
44
|
+
deepCompare,
|
|
44
45
|
} = {
|
|
45
46
|
...useFetchDefaultOptions,
|
|
46
47
|
...globalConfig.useFetchConfig,
|
|
@@ -52,36 +53,35 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
52
53
|
const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });
|
|
53
54
|
const refreshDebounce = useDebounce({ delay: refreshTime });
|
|
54
55
|
|
|
55
|
-
const { cacheKey,
|
|
56
|
+
const { cacheKey, queryKey, client } = request;
|
|
56
57
|
const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;
|
|
57
58
|
|
|
58
59
|
const ignoreReact18DoubleRender = useRef(true);
|
|
59
|
-
const logger = useRef(loggerManager.
|
|
60
|
+
const logger = useRef(loggerManager.initialize(client, "useFetch")).current;
|
|
60
61
|
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
|
|
61
62
|
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
|
|
62
63
|
|
|
63
64
|
/**
|
|
64
65
|
* State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues
|
|
65
66
|
*/
|
|
66
|
-
const [state, actions, { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing }] =
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
});
|
|
67
|
+
const [state, actions, { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing }] = useTrackedState<R>({
|
|
68
|
+
logger,
|
|
69
|
+
request: request as R,
|
|
70
|
+
dispatcher,
|
|
71
|
+
initialResponse,
|
|
72
|
+
deepCompare,
|
|
73
|
+
dependencyTracking,
|
|
74
|
+
disabled,
|
|
75
|
+
revalidate,
|
|
76
|
+
});
|
|
77
77
|
|
|
78
78
|
/**
|
|
79
79
|
* Handles the data exchange with the core logic - responses, loading, downloading etc
|
|
80
80
|
*/
|
|
81
|
-
const [callbacks, listeners] = useRequestEvents({
|
|
81
|
+
const [callbacks, listeners] = useRequestEvents<R>({
|
|
82
82
|
logger,
|
|
83
83
|
actions,
|
|
84
|
-
request,
|
|
84
|
+
request: request as R,
|
|
85
85
|
dispatcher,
|
|
86
86
|
setCacheData,
|
|
87
87
|
getIsDataProcessing,
|
|
@@ -94,10 +94,10 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
94
94
|
// ******************
|
|
95
95
|
const handleFetch = () => {
|
|
96
96
|
if (!disabled) {
|
|
97
|
-
logger.debug(`Fetching data
|
|
98
|
-
dispatcher.add(request);
|
|
97
|
+
logger.debug({ title: `Fetching data`, type: "system", extra: { request } });
|
|
98
|
+
dispatcher.add(request as R);
|
|
99
99
|
} else {
|
|
100
|
-
logger.debug(`Cannot add to fetch queue`, { disabled });
|
|
100
|
+
logger.debug({ title: `Cannot add to fetch queue`, type: "system", extra: { disabled } });
|
|
101
101
|
}
|
|
102
102
|
};
|
|
103
103
|
|
|
@@ -115,15 +115,15 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
115
115
|
const isBlurred = !appManager.isFocused;
|
|
116
116
|
|
|
117
117
|
// If window tab is not active should we refresh the cache
|
|
118
|
-
const isFetching = dispatcher.hasRunningRequests(request.
|
|
119
|
-
const isQueued = dispatcher.getIsActiveQueue(request.
|
|
118
|
+
const isFetching = dispatcher.hasRunningRequests(request.queryKey);
|
|
119
|
+
const isQueued = dispatcher.getIsActiveQueue(request.queryKey);
|
|
120
120
|
const isActive = isFetching || isQueued;
|
|
121
121
|
const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;
|
|
122
122
|
const canRefreshFocused = !isBlurred && !isActive;
|
|
123
123
|
|
|
124
124
|
if (canRefreshBlurred || canRefreshFocused) {
|
|
125
125
|
handleFetch();
|
|
126
|
-
logger.debug(`Performing refresh request
|
|
126
|
+
logger.debug({ title: `Performing refresh request`, type: "system", extra: { request } });
|
|
127
127
|
}
|
|
128
128
|
|
|
129
129
|
// Start new refresh counter
|
|
@@ -131,23 +131,9 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
131
131
|
});
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
} else if (invalidateKey && !(invalidateKey instanceof Request)) {
|
|
138
|
-
cache.invalidate(invalidateKey);
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
const refetch = (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => {
|
|
143
|
-
if (invalidateKey && Array.isArray(invalidateKey)) {
|
|
144
|
-
invalidateKey.forEach(handleInvalidation);
|
|
145
|
-
} else if (invalidateKey && !Array.isArray(invalidateKey)) {
|
|
146
|
-
handleInvalidation(invalidateKey);
|
|
147
|
-
} else {
|
|
148
|
-
handleFetch();
|
|
149
|
-
handleRefresh();
|
|
150
|
-
}
|
|
134
|
+
const refetch = () => {
|
|
135
|
+
handleFetch();
|
|
136
|
+
handleRefresh();
|
|
151
137
|
};
|
|
152
138
|
|
|
153
139
|
// ******************
|
|
@@ -156,8 +142,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
156
142
|
|
|
157
143
|
// This help us to check for currently running requests
|
|
158
144
|
const getIsFetchingIdentity = () => {
|
|
159
|
-
// We need to check if the
|
|
160
|
-
return dispatcher.getRunningRequests(
|
|
145
|
+
// We need to check if the queryKey have the same cacheKey elements ongoing
|
|
146
|
+
return dispatcher.getRunningRequests(queryKey).some((running) => running.request.cacheKey === cacheKey);
|
|
161
147
|
};
|
|
162
148
|
|
|
163
149
|
const initialFetchData = () => {
|
|
@@ -181,7 +167,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
181
167
|
* This way it will not wait for debouncing but fetch data right away
|
|
182
168
|
*/
|
|
183
169
|
if (bounce) {
|
|
184
|
-
logger.debug(`Bounce request with ${bounceType}`, {
|
|
170
|
+
logger.debug({ title: `Bounce request with ${bounceType}`, type: "system", extra: { queryKey, request } });
|
|
185
171
|
bounceFunction(() => handleFetch());
|
|
186
172
|
} else {
|
|
187
173
|
handleFetch();
|
|
@@ -196,8 +182,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
196
182
|
// ******************
|
|
197
183
|
|
|
198
184
|
const handleMountEvents = () => {
|
|
199
|
-
addCacheDataListener(request);
|
|
200
|
-
addLifecycleListeners(request);
|
|
185
|
+
addCacheDataListener(request as R);
|
|
186
|
+
addLifecycleListeners(request as R);
|
|
201
187
|
|
|
202
188
|
const focusUnmount = appManager.events.onFocus(() => {
|
|
203
189
|
if (refetchOnFocus) {
|
|
@@ -218,7 +204,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
218
204
|
}
|
|
219
205
|
});
|
|
220
206
|
|
|
221
|
-
const invalidateUnmount = cache.events.
|
|
207
|
+
const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleFetch);
|
|
208
|
+
const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleFetch);
|
|
222
209
|
|
|
223
210
|
const unmount = () => {
|
|
224
211
|
clearCacheDataListener();
|
|
@@ -226,6 +213,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
226
213
|
blurUnmount();
|
|
227
214
|
onlineUnmount();
|
|
228
215
|
invalidateUnmount();
|
|
216
|
+
deletionUnmount();
|
|
229
217
|
};
|
|
230
218
|
|
|
231
219
|
return unmount;
|
|
@@ -278,7 +266,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
278
266
|
},
|
|
279
267
|
get status() {
|
|
280
268
|
setRenderKey("status");
|
|
281
|
-
return state.status
|
|
269
|
+
return state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>;
|
|
282
270
|
},
|
|
283
271
|
get success() {
|
|
284
272
|
setRenderKey("success");
|
|
@@ -286,19 +274,23 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
286
274
|
},
|
|
287
275
|
get extra() {
|
|
288
276
|
setRenderKey("extra");
|
|
289
|
-
return state.extra
|
|
277
|
+
return state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>;
|
|
290
278
|
},
|
|
291
279
|
get retries() {
|
|
292
280
|
setRenderKey("retries");
|
|
293
281
|
return state.retries;
|
|
294
282
|
},
|
|
295
|
-
get
|
|
296
|
-
setRenderKey("
|
|
297
|
-
return state.
|
|
283
|
+
get responseTimestamp() {
|
|
284
|
+
setRenderKey("responseTimestamp");
|
|
285
|
+
return state.responseTimestamp;
|
|
286
|
+
},
|
|
287
|
+
get requestTimestamp() {
|
|
288
|
+
setRenderKey("requestTimestamp");
|
|
289
|
+
return state.requestTimestamp;
|
|
298
290
|
},
|
|
299
291
|
bounce: getBounceData(bounceData),
|
|
300
292
|
...actions,
|
|
301
|
-
...callbacks,
|
|
293
|
+
...(callbacks as any),
|
|
302
294
|
refetch,
|
|
303
295
|
};
|
|
304
296
|
};
|
|
@@ -1,10 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
RequestInstance,
|
|
3
|
+
NullableType,
|
|
4
|
+
ExtractAdapterResolvedType,
|
|
5
|
+
ExtendRequest,
|
|
6
|
+
EmptyTypes,
|
|
7
|
+
RequestSendOptionsType,
|
|
8
|
+
} from "@hyper-fetch/core";
|
|
2
9
|
|
|
3
10
|
import { UseRequestEventsActionsType, UseTrackedStateActions, UseTrackedStateType } from "helpers";
|
|
4
|
-
import { InvalidationKeyType } from "types";
|
|
5
11
|
import { isEqual } from "utils";
|
|
6
12
|
|
|
7
|
-
export type
|
|
13
|
+
export type UseFetchRequest<R extends RequestInstance> = ExtendRequest<
|
|
14
|
+
R,
|
|
15
|
+
{
|
|
16
|
+
hasData: RequestSendOptionsType<R>["payload"] extends EmptyTypes ? true : false;
|
|
17
|
+
hasParams: RequestSendOptionsType<R>["params"] extends EmptyTypes ? true : false;
|
|
18
|
+
hasQuery: RequestSendOptionsType<R>["queryParams"] extends EmptyTypes ? true : false;
|
|
19
|
+
}
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
export type UseFetchOptionsType<R extends RequestInstance> = {
|
|
8
23
|
/**
|
|
9
24
|
* Refetch dependencies
|
|
10
25
|
*/
|
|
@@ -24,7 +39,7 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
|
|
|
24
39
|
/**
|
|
25
40
|
* If cache is empty we can use placeholder data.
|
|
26
41
|
*/
|
|
27
|
-
|
|
42
|
+
initialResponse?: NullableType<Partial<ExtractAdapterResolvedType<UseFetchRequest<R>>>>;
|
|
28
43
|
/**
|
|
29
44
|
* Enable/disable refresh data
|
|
30
45
|
*/
|
|
@@ -67,6 +82,10 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
|
|
|
67
82
|
* How long it should bounce requests.
|
|
68
83
|
*/
|
|
69
84
|
bounceTime?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Not applicable for debounce mode
|
|
87
|
+
*/
|
|
88
|
+
bounceTimeout?: void;
|
|
70
89
|
}
|
|
71
90
|
| {
|
|
72
91
|
/**
|
|
@@ -84,9 +103,9 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
|
|
|
84
103
|
}
|
|
85
104
|
);
|
|
86
105
|
|
|
87
|
-
export type UseFetchReturnType<
|
|
88
|
-
UseTrackedStateActions<
|
|
89
|
-
UseRequestEventsActionsType<
|
|
106
|
+
export type UseFetchReturnType<R extends RequestInstance> = UseTrackedStateType<UseFetchRequest<R>> &
|
|
107
|
+
UseTrackedStateActions<UseFetchRequest<R>> &
|
|
108
|
+
UseRequestEventsActionsType<UseFetchRequest<R>> & {
|
|
90
109
|
/**
|
|
91
110
|
* Data related to current state of the bounce usage
|
|
92
111
|
*/
|
|
@@ -101,7 +120,7 @@ export type UseFetchReturnType<T extends RequestInstance> = UseTrackedStateType<
|
|
|
101
120
|
reset: () => void;
|
|
102
121
|
};
|
|
103
122
|
/**
|
|
104
|
-
* Refetch current request
|
|
123
|
+
* Refetch current request
|
|
105
124
|
*/
|
|
106
|
-
refetch: (
|
|
125
|
+
refetch: () => void;
|
|
107
126
|
};
|
|
@@ -1,21 +1,16 @@
|
|
|
1
|
-
import { useRef } from "react";
|
|
2
1
|
import { useDidUpdate, useWillUnmount } from "@better-hooks/lifecycle";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
ExtractListenerAdapterType,
|
|
6
|
-
ExtractSocketExtraType,
|
|
7
|
-
ExtractListenerResponseType,
|
|
8
|
-
} from "@hyper-fetch/sockets";
|
|
2
|
+
import { ListenerInstance, ExtractListenerResponseType } from "@hyper-fetch/sockets";
|
|
3
|
+
import { useRef } from "react";
|
|
9
4
|
|
|
10
5
|
import { useSocketState } from "helpers";
|
|
11
6
|
import { UseListenerOptionsType } from "hooks/use-listener";
|
|
12
|
-
import {
|
|
7
|
+
import { useProvider } from "provider";
|
|
13
8
|
|
|
14
9
|
export const useListener = <ListenerType extends ListenerInstance>(
|
|
15
10
|
listener: ListenerType,
|
|
16
|
-
options
|
|
11
|
+
options?: UseListenerOptionsType,
|
|
17
12
|
) => {
|
|
18
|
-
const
|
|
13
|
+
const { config: globalConfig } = useProvider();
|
|
19
14
|
const { dependencyTracking } = { ...globalConfig.useListener, ...options };
|
|
20
15
|
const [state, actions, callbacks, { setRenderKey }] = useSocketState(listener.socket, { dependencyTracking });
|
|
21
16
|
const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);
|
|
@@ -25,11 +20,7 @@ export const useListener = <ListenerType extends ListenerInstance>(
|
|
|
25
20
|
*/
|
|
26
21
|
|
|
27
22
|
const onEventCallback = useRef<
|
|
28
|
-
|
|
|
29
|
-
| ((response: {
|
|
30
|
-
data: ExtractListenerResponseType<ListenerType>;
|
|
31
|
-
extra: ExtractSocketExtraType<ExtractListenerAdapterType<ListenerType>>;
|
|
32
|
-
}) => void)
|
|
23
|
+
null | ((response: { data: ExtractListenerResponseType<ListenerType>; extra: Record<string, any> }) => void)
|
|
33
24
|
>(null);
|
|
34
25
|
|
|
35
26
|
/**
|
|
@@ -42,12 +33,11 @@ export const useListener = <ListenerType extends ListenerInstance>(
|
|
|
42
33
|
|
|
43
34
|
const listen = () => {
|
|
44
35
|
stopListener();
|
|
45
|
-
removeListenerRef.current = listener.listen({
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
},
|
|
36
|
+
removeListenerRef.current = listener.listen(({ data, extra }) => {
|
|
37
|
+
onEventCallback.current?.({ data, extra });
|
|
38
|
+
actions.setData(data);
|
|
39
|
+
actions.setExtra(extra);
|
|
40
|
+
actions.setTimestamp(+new Date());
|
|
51
41
|
});
|
|
52
42
|
};
|
|
53
43
|
|
|
@@ -78,6 +68,10 @@ export const useListener = <ListenerType extends ListenerInstance>(
|
|
|
78
68
|
setRenderKey("data");
|
|
79
69
|
return state.data;
|
|
80
70
|
},
|
|
71
|
+
get extra() {
|
|
72
|
+
setRenderKey("extra");
|
|
73
|
+
return state.extra;
|
|
74
|
+
},
|
|
81
75
|
get connected() {
|
|
82
76
|
setRenderKey("connected");
|
|
83
77
|
return state.connected;
|
|
@@ -1,9 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { useDidMount, useDidUpdate } from "@better-hooks/lifecycle";
|
|
1
|
+
import { RequestInstance, getRequestDispatcher, QueueItemType, QueueDataType } from "@hyper-fetch/core";
|
|
2
|
+
import { useState, useEffect, useCallback } from "react";
|
|
4
3
|
|
|
5
4
|
import { UseQueueOptionsType, useQueueDefaultOptions, QueueRequest, UseQueueReturnType } from "hooks/use-queue";
|
|
6
|
-
import {
|
|
5
|
+
import { useProvider } from "provider";
|
|
6
|
+
|
|
7
|
+
const canUpdate = (
|
|
8
|
+
item: Pick<QueueRequest<RequestInstance>, "success" | "failed" | "canceled" | "removed" | "resolved">,
|
|
9
|
+
) => {
|
|
10
|
+
if (item.success || item.failed) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
};
|
|
7
15
|
|
|
8
16
|
/**
|
|
9
17
|
* This hook allows to control dispatchers request queues
|
|
@@ -13,22 +21,20 @@ import { useConfigProvider } from "config-provider";
|
|
|
13
21
|
*/
|
|
14
22
|
export const useQueue = <Request extends RequestInstance>(
|
|
15
23
|
request: Request,
|
|
16
|
-
options
|
|
24
|
+
options?: UseQueueOptionsType,
|
|
17
25
|
): UseQueueReturnType<Request> => {
|
|
18
26
|
// Build the configuration options
|
|
19
|
-
const
|
|
20
|
-
const {
|
|
27
|
+
const { config: globalConfig } = useProvider();
|
|
28
|
+
const { dispatcherType, keepFinishedRequests } = {
|
|
21
29
|
...useQueueDefaultOptions,
|
|
22
30
|
...globalConfig.useQueueConfig,
|
|
23
31
|
...options,
|
|
24
32
|
};
|
|
25
33
|
|
|
26
|
-
const { abortKey,
|
|
34
|
+
const { abortKey, queryKey, client } = request;
|
|
27
35
|
const { requestManager } = client;
|
|
28
36
|
|
|
29
|
-
const [dispatcher] = getRequestDispatcher(request,
|
|
30
|
-
|
|
31
|
-
const unmountCallbacks = useRef<null | VoidFunction>(null);
|
|
37
|
+
const [dispatcher] = getRequestDispatcher(request, dispatcherType);
|
|
32
38
|
|
|
33
39
|
const [stopped, setStopped] = useState(false);
|
|
34
40
|
const [requests, setRequests] = useState<QueueRequest<Request>[]>([]);
|
|
@@ -37,60 +43,124 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
37
43
|
// Mapping
|
|
38
44
|
// ******************
|
|
39
45
|
|
|
40
|
-
const createRequestsArray = (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
46
|
+
const createRequestsArray = useCallback(
|
|
47
|
+
(queueElements: QueueItemType<Request>[], prevRequests?: QueueRequest<Request>[]): QueueRequest<Request>[] => {
|
|
48
|
+
const newRequests = queueElements
|
|
49
|
+
// Keep only unique requests
|
|
50
|
+
.filter((el) => !prevRequests?.some((prevEl) => prevEl.requestId === el.requestId))
|
|
51
|
+
.map<QueueRequest<Request>>((req) => ({
|
|
52
|
+
failed: false,
|
|
53
|
+
canceled: false,
|
|
54
|
+
removed: false,
|
|
55
|
+
success: false,
|
|
56
|
+
...req,
|
|
57
|
+
downloading: {
|
|
58
|
+
progress: 0,
|
|
59
|
+
timeLeft: 0,
|
|
60
|
+
sizeLeft: 0,
|
|
61
|
+
total: 0,
|
|
62
|
+
loaded: 0,
|
|
63
|
+
startTimestamp: 0,
|
|
64
|
+
},
|
|
65
|
+
uploading: {
|
|
66
|
+
progress: 0,
|
|
67
|
+
timeLeft: 0,
|
|
68
|
+
sizeLeft: 0,
|
|
69
|
+
total: 0,
|
|
70
|
+
loaded: 0,
|
|
71
|
+
startTimestamp: 0,
|
|
72
|
+
},
|
|
73
|
+
stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),
|
|
74
|
+
startRequest: () => dispatcher.startRequest(queryKey, req.requestId),
|
|
75
|
+
deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),
|
|
76
|
+
}));
|
|
77
|
+
|
|
78
|
+
if (keepFinishedRequests && prevRequests) {
|
|
79
|
+
return [...prevRequests, ...newRequests];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return newRequests;
|
|
83
|
+
},
|
|
84
|
+
[abortKey, dispatcher, queryKey, keepFinishedRequests],
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {
|
|
88
|
+
setRequests((prev) =>
|
|
89
|
+
prev.map((el) => {
|
|
90
|
+
if (el.requestId === requestId && canUpdate(el)) {
|
|
91
|
+
return { ...el, ...data };
|
|
92
|
+
}
|
|
93
|
+
return el;
|
|
94
|
+
}),
|
|
95
|
+
);
|
|
96
|
+
}, []);
|
|
52
97
|
|
|
53
98
|
// ******************
|
|
54
99
|
// State
|
|
55
100
|
// ******************
|
|
56
101
|
|
|
57
102
|
const getInitialState = () => {
|
|
58
|
-
const requestQueue = dispatcher.getQueue<Request>(
|
|
103
|
+
const requestQueue = dispatcher.getQueue<Request>(queryKey);
|
|
59
104
|
|
|
60
105
|
setStopped(requestQueue.stopped);
|
|
61
106
|
setRequests(createRequestsArray(requestQueue.requests));
|
|
62
107
|
};
|
|
63
108
|
|
|
64
|
-
const updateQueueState = (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
109
|
+
const updateQueueState = useCallback(
|
|
110
|
+
(values: QueueDataType<Request>) => {
|
|
111
|
+
setStopped(values.stopped);
|
|
112
|
+
setRequests((prev) => createRequestsArray(values.requests, prev));
|
|
113
|
+
},
|
|
114
|
+
[createRequestsArray],
|
|
115
|
+
);
|
|
68
116
|
|
|
69
117
|
// ******************
|
|
70
118
|
// Events
|
|
71
119
|
// ******************
|
|
72
120
|
|
|
73
121
|
const mountEvents = () => {
|
|
74
|
-
const unmountChange = dispatcher.events.
|
|
75
|
-
const unmountStatus = dispatcher.events.
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
122
|
+
const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);
|
|
123
|
+
const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);
|
|
124
|
+
|
|
125
|
+
const unmountFailed = requestManager.events.onResponse(({ requestId, response }) => {
|
|
126
|
+
if (!response.success) {
|
|
127
|
+
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, failed: true } : el)));
|
|
128
|
+
} else {
|
|
129
|
+
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, success: true } : el)));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {
|
|
133
|
+
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));
|
|
79
134
|
});
|
|
80
135
|
|
|
81
|
-
const
|
|
82
|
-
|
|
136
|
+
const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {
|
|
137
|
+
setRequests((prev) =>
|
|
138
|
+
prev.map((el) => (el.requestId === requestId && canUpdate(el) ? { ...el, removed: true } : el)),
|
|
139
|
+
);
|
|
83
140
|
});
|
|
84
141
|
|
|
142
|
+
const unmountDownload = requestManager.events.onDownloadProgress(
|
|
143
|
+
({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {
|
|
144
|
+
mergePayloadType(requestId, { downloading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });
|
|
145
|
+
},
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
const unmountUpload = requestManager.events.onUploadProgress(
|
|
149
|
+
({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {
|
|
150
|
+
mergePayloadType(requestId, { uploading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });
|
|
151
|
+
},
|
|
152
|
+
);
|
|
153
|
+
|
|
85
154
|
const unmount = () => {
|
|
86
155
|
unmountStatus();
|
|
87
156
|
unmountChange();
|
|
88
157
|
unmountDownload();
|
|
89
158
|
unmountUpload();
|
|
159
|
+
unmountFailed();
|
|
160
|
+
unmountCanceled();
|
|
161
|
+
unmountRemoved();
|
|
90
162
|
};
|
|
91
163
|
|
|
92
|
-
unmountCallbacks.current?.();
|
|
93
|
-
unmountCallbacks.current = unmount;
|
|
94
164
|
return unmount;
|
|
95
165
|
};
|
|
96
166
|
|
|
@@ -98,15 +168,26 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
98
168
|
// Lifecycle
|
|
99
169
|
// ******************
|
|
100
170
|
|
|
101
|
-
|
|
171
|
+
useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);
|
|
102
172
|
|
|
103
|
-
|
|
173
|
+
useEffect(mountEvents, [
|
|
174
|
+
stopped,
|
|
175
|
+
requests,
|
|
176
|
+
setRequests,
|
|
177
|
+
setStopped,
|
|
178
|
+
queryKey,
|
|
179
|
+
dispatcher.events,
|
|
180
|
+
requestManager.events,
|
|
181
|
+
updateQueueState,
|
|
182
|
+
mergePayloadType,
|
|
183
|
+
]);
|
|
104
184
|
|
|
105
185
|
return {
|
|
106
186
|
stopped,
|
|
107
187
|
requests,
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
188
|
+
dispatcher,
|
|
189
|
+
stop: () => dispatcher.stop(queryKey),
|
|
190
|
+
pause: () => dispatcher.pause(queryKey),
|
|
191
|
+
start: () => dispatcher.start(queryKey),
|
|
111
192
|
};
|
|
112
193
|
};
|