@hyper-fetch/react 6.0.0 → 7.0.0
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 +179 -157
- package/dist/{index.esm.js → index.js} +500 -435
- package/dist/index.js.map +7 -0
- package/package.json +12 -13
- package/src/helpers/use-request-events/use-request-events.hooks.ts +73 -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 +79 -98
- package/src/helpers/use-tracked-state/use-tracked-state.types.ts +44 -25
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +79 -34
- 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 -82
- 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 -1514
- 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,34 +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
|
-
|
|
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
|
+
});
|
|
75
77
|
|
|
76
78
|
/**
|
|
77
79
|
* Handles the data exchange with the core logic - responses, loading, downloading etc
|
|
78
80
|
*/
|
|
79
|
-
const [callbacks, listeners] = useRequestEvents({
|
|
81
|
+
const [callbacks, listeners] = useRequestEvents<R>({
|
|
80
82
|
logger,
|
|
81
83
|
actions,
|
|
82
|
-
request,
|
|
84
|
+
request: request as R,
|
|
83
85
|
dispatcher,
|
|
84
86
|
setCacheData,
|
|
85
87
|
getIsDataProcessing,
|
|
@@ -92,15 +94,10 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
92
94
|
// ******************
|
|
93
95
|
const handleFetch = () => {
|
|
94
96
|
if (!disabled) {
|
|
95
|
-
logger.debug(`Fetching data
|
|
96
|
-
dispatcher.add(request);
|
|
97
|
-
const queue = dispatcher.getQueue(request.queueKey);
|
|
98
|
-
// We want fast initial loading state if not paused / disabled
|
|
99
|
-
if (!queue.stopped && queue.requests.length) {
|
|
100
|
-
actions.setLoading(true);
|
|
101
|
-
}
|
|
97
|
+
logger.debug({ title: `Fetching data`, type: "system", extra: { request } });
|
|
98
|
+
dispatcher.add(request as R);
|
|
102
99
|
} else {
|
|
103
|
-
logger.debug(`Cannot add to fetch queue`, { disabled });
|
|
100
|
+
logger.debug({ title: `Cannot add to fetch queue`, type: "system", extra: { disabled } });
|
|
104
101
|
}
|
|
105
102
|
};
|
|
106
103
|
|
|
@@ -118,15 +115,15 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
118
115
|
const isBlurred = !appManager.isFocused;
|
|
119
116
|
|
|
120
117
|
// If window tab is not active should we refresh the cache
|
|
121
|
-
const isFetching = dispatcher.hasRunningRequests(request.
|
|
122
|
-
const isQueued = dispatcher.getIsActiveQueue(request.
|
|
118
|
+
const isFetching = dispatcher.hasRunningRequests(request.queryKey);
|
|
119
|
+
const isQueued = dispatcher.getIsActiveQueue(request.queryKey);
|
|
123
120
|
const isActive = isFetching || isQueued;
|
|
124
121
|
const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;
|
|
125
122
|
const canRefreshFocused = !isBlurred && !isActive;
|
|
126
123
|
|
|
127
124
|
if (canRefreshBlurred || canRefreshFocused) {
|
|
128
125
|
handleFetch();
|
|
129
|
-
logger.debug(`Performing refresh request
|
|
126
|
+
logger.debug({ title: `Performing refresh request`, type: "system", extra: { request } });
|
|
130
127
|
}
|
|
131
128
|
|
|
132
129
|
// Start new refresh counter
|
|
@@ -134,23 +131,9 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
134
131
|
});
|
|
135
132
|
}
|
|
136
133
|
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
} else if (invalidateKey && !(invalidateKey instanceof Request)) {
|
|
141
|
-
cache.invalidate(invalidateKey);
|
|
142
|
-
}
|
|
143
|
-
};
|
|
144
|
-
|
|
145
|
-
const refetch = (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => {
|
|
146
|
-
if (invalidateKey && Array.isArray(invalidateKey)) {
|
|
147
|
-
invalidateKey.forEach(handleInvalidation);
|
|
148
|
-
} else if (invalidateKey && !Array.isArray(invalidateKey)) {
|
|
149
|
-
handleInvalidation(invalidateKey);
|
|
150
|
-
} else {
|
|
151
|
-
handleFetch();
|
|
152
|
-
handleRefresh();
|
|
153
|
-
}
|
|
134
|
+
const refetch = () => {
|
|
135
|
+
handleFetch();
|
|
136
|
+
handleRefresh();
|
|
154
137
|
};
|
|
155
138
|
|
|
156
139
|
// ******************
|
|
@@ -159,8 +142,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
159
142
|
|
|
160
143
|
// This help us to check for currently running requests
|
|
161
144
|
const getIsFetchingIdentity = () => {
|
|
162
|
-
// We need to check if the
|
|
163
|
-
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);
|
|
164
147
|
};
|
|
165
148
|
|
|
166
149
|
const initialFetchData = () => {
|
|
@@ -184,7 +167,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
184
167
|
* This way it will not wait for debouncing but fetch data right away
|
|
185
168
|
*/
|
|
186
169
|
if (bounce) {
|
|
187
|
-
logger.debug(`Bounce request with ${bounceType}`, {
|
|
170
|
+
logger.debug({ title: `Bounce request with ${bounceType}`, type: "system", extra: { queryKey, request } });
|
|
188
171
|
bounceFunction(() => handleFetch());
|
|
189
172
|
} else {
|
|
190
173
|
handleFetch();
|
|
@@ -199,8 +182,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
199
182
|
// ******************
|
|
200
183
|
|
|
201
184
|
const handleMountEvents = () => {
|
|
202
|
-
addCacheDataListener(request);
|
|
203
|
-
addLifecycleListeners(request);
|
|
185
|
+
addCacheDataListener(request as R);
|
|
186
|
+
addLifecycleListeners(request as R);
|
|
204
187
|
|
|
205
188
|
const focusUnmount = appManager.events.onFocus(() => {
|
|
206
189
|
if (refetchOnFocus) {
|
|
@@ -221,7 +204,8 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
221
204
|
}
|
|
222
205
|
});
|
|
223
206
|
|
|
224
|
-
const invalidateUnmount = cache.events.
|
|
207
|
+
const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleFetch);
|
|
208
|
+
const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleFetch);
|
|
225
209
|
|
|
226
210
|
const unmount = () => {
|
|
227
211
|
clearCacheDataListener();
|
|
@@ -229,6 +213,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
229
213
|
blurUnmount();
|
|
230
214
|
onlineUnmount();
|
|
231
215
|
invalidateUnmount();
|
|
216
|
+
deletionUnmount();
|
|
232
217
|
};
|
|
233
218
|
|
|
234
219
|
return unmount;
|
|
@@ -281,7 +266,7 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
281
266
|
},
|
|
282
267
|
get status() {
|
|
283
268
|
setRenderKey("status");
|
|
284
|
-
return state.status
|
|
269
|
+
return state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>;
|
|
285
270
|
},
|
|
286
271
|
get success() {
|
|
287
272
|
setRenderKey("success");
|
|
@@ -289,19 +274,23 @@ export const useFetch = <RequestType extends RequestInstance>(
|
|
|
289
274
|
},
|
|
290
275
|
get extra() {
|
|
291
276
|
setRenderKey("extra");
|
|
292
|
-
return state.extra
|
|
277
|
+
return state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>;
|
|
293
278
|
},
|
|
294
279
|
get retries() {
|
|
295
280
|
setRenderKey("retries");
|
|
296
281
|
return state.retries;
|
|
297
282
|
},
|
|
298
|
-
get
|
|
299
|
-
setRenderKey("
|
|
300
|
-
return state.
|
|
283
|
+
get responseTimestamp() {
|
|
284
|
+
setRenderKey("responseTimestamp");
|
|
285
|
+
return state.responseTimestamp;
|
|
286
|
+
},
|
|
287
|
+
get requestTimestamp() {
|
|
288
|
+
setRenderKey("requestTimestamp");
|
|
289
|
+
return state.requestTimestamp;
|
|
301
290
|
},
|
|
302
291
|
bounce: getBounceData(bounceData),
|
|
303
292
|
...actions,
|
|
304
|
-
...callbacks,
|
|
293
|
+
...(callbacks as any),
|
|
305
294
|
refetch,
|
|
306
295
|
};
|
|
307
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
|
};
|