@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.
Files changed (45) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/index.d.ts +167 -166
  4. package/dist/{index.esm.js → index.js} +462 -431
  5. package/dist/index.js.map +7 -0
  6. package/package.json +12 -13
  7. package/src/helpers/use-request-events/use-request-events.hooks.ts +79 -80
  8. package/src/helpers/use-request-events/use-request-events.types.ts +24 -22
  9. package/src/helpers/use-socket-state/use-socket-state.constants.ts +4 -1
  10. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +39 -29
  11. package/src/helpers/use-socket-state/use-socket-state.types.ts +4 -1
  12. package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +4 -3
  13. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +82 -115
  14. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +42 -25
  15. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +45 -41
  16. package/src/hooks/use-app-manager/use-app-manager.hooks.ts +2 -2
  17. package/src/hooks/use-cache/use-cache.constants.ts +1 -1
  18. package/src/hooks/use-cache/use-cache.hooks.ts +32 -27
  19. package/src/hooks/use-cache/use-cache.types.ts +4 -22
  20. package/src/hooks/use-emitter/use-emitter.hooks.ts +50 -18
  21. package/src/hooks/use-fetch/use-fetch.constants.ts +6 -5
  22. package/src/hooks/use-fetch/use-fetch.hooks.ts +71 -79
  23. package/src/hooks/use-fetch/use-fetch.types.ts +28 -9
  24. package/src/hooks/use-listener/use-listener.hooks.ts +15 -21
  25. package/src/hooks/use-queue/use-queue.constants.ts +2 -1
  26. package/src/hooks/use-queue/use-queue.hooks.ts +123 -42
  27. package/src/hooks/use-queue/use-queue.types.ts +14 -5
  28. package/src/hooks/use-submit/use-submit.constants.ts +3 -3
  29. package/src/hooks/use-submit/use-submit.hooks.ts +39 -53
  30. package/src/hooks/use-submit/use-submit.types.ts +5 -6
  31. package/src/index.ts +1 -3
  32. package/src/provider/index.ts +2 -0
  33. package/src/{config-provider/config-provider.tsx → provider/provider.tsx} +8 -5
  34. package/src/{config-provider/config-provider.types.ts → provider/provider.types.ts} +15 -8
  35. package/src/utils/deep-equal.utils.ts +1 -3
  36. package/tsconfig.json +2 -2
  37. package/dist/index.cjs.js +0 -1550
  38. package/dist/index.cjs.js.map +0 -7
  39. package/dist/index.esm.js.map +0 -7
  40. package/src/config-provider/index.ts +0 -2
  41. package/src/hooks/use-event-messages/index.ts +0 -2
  42. package/src/hooks/use-event-messages/use-event-messages.hooks.ts +0 -69
  43. package/src/hooks/use-event-messages/use-event-messages.types.ts +0 -4
  44. package/src/types/index.ts +0 -1
  45. package/src/types/invalidation.types.ts +0 -3
@@ -1,18 +1,23 @@
1
- import { ProgressType, RequestInstance, QueueElementType } from "@hyper-fetch/core";
1
+ import { ProgressType, RequestInstance, QueueItemType, Dispatcher, ExtractAdapterType } from "@hyper-fetch/core";
2
2
 
3
3
  export type UseQueueOptionsType = {
4
- queueType?: "auto" | "fetch" | "submit";
4
+ dispatcherType?: "auto" | "fetch" | "submit";
5
+ keepFinishedRequests?: boolean;
5
6
  };
6
7
 
7
- export type QueueRequest<Request extends RequestInstance> = QueueElementType<Request> & {
8
+ export type QueueRequest<Request extends RequestInstance> = QueueItemType<Request> & {
9
+ failed?: boolean;
10
+ canceled?: boolean;
11
+ removed?: boolean;
12
+ success?: boolean;
8
13
  /**
9
14
  * Uploading progress for given request
10
15
  */
11
- uploading?: ProgressType;
16
+ uploading: ProgressType;
12
17
  /**
13
18
  * Downloading progress for given request
14
19
  */
15
- downloading?: ProgressType;
20
+ downloading: ProgressType;
16
21
  /**
17
22
  * Callback which allow to start previously stopped request.
18
23
  */
@@ -36,6 +41,10 @@ export type UseQueueReturnType<T extends RequestInstance> = {
36
41
  * List of requests for provided request
37
42
  */
38
43
  requests: QueueRequest<T>[];
44
+ /**
45
+ * Request dispatcher instance
46
+ */
47
+ dispatcher: Dispatcher<ExtractAdapterType<T>>;
39
48
  /**
40
49
  * Callback which allow to stop queue, it will cancel ongoing requests.
41
50
  */
@@ -2,14 +2,14 @@ import { RequestInstance, RequiredKeys } from "@hyper-fetch/core";
2
2
 
3
3
  import { UseSubmitOptionsType } from "./use-submit.types";
4
4
 
5
- type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, "initialData">> & {
6
- initialData: null;
5
+ type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, "initialResponse">> & {
6
+ initialResponse: null;
7
7
  };
8
8
 
9
9
  export const useSubmitDefaultOptions: DefaultOptionsType = {
10
10
  disabled: false,
11
11
  dependencyTracking: true,
12
- initialData: null,
12
+ initialResponse: null,
13
13
  bounce: false,
14
14
  bounceType: "debounce",
15
15
  bounceTime: 400,
@@ -1,11 +1,8 @@
1
- import { useMemo, useRef } from "react";
2
1
  import {
3
- Request,
4
- getRequestKey,
5
- ExtractAdapterReturnType,
2
+ ExtractAdapterResolvedType,
6
3
  RequestInstance,
7
4
  sendRequest,
8
- ResponseReturnType,
5
+ ResponseType,
9
6
  ExtractResponseType,
10
7
  ExtractErrorType,
11
8
  RequestSendOptionsType,
@@ -14,12 +11,12 @@ import {
14
11
  } from "@hyper-fetch/core";
15
12
  import { useDidMount } from "@better-hooks/lifecycle";
16
13
  import { useDebounce, useThrottle } from "@better-hooks/performance";
14
+ import { useMemo, useRef } from "react";
17
15
 
18
16
  import { UseSubmitOptionsType, useSubmitDefaultOptions, UseSubmitReturnType } from "hooks/use-submit";
19
17
  import { useTrackedState, useRequestEvents } from "helpers";
20
- import { useConfigProvider } from "config-provider";
18
+ import { useProvider } from "provider";
21
19
  import { getBounceData } from "utils";
22
- import { InvalidationKeyType } from "types";
23
20
 
24
21
  /**
25
22
  * This hooks aims to mutate data on the server.
@@ -29,10 +26,10 @@ import { InvalidationKeyType } from "types";
29
26
  */
30
27
  export const useSubmit = <RequestType extends RequestInstance>(
31
28
  request: RequestType,
32
- options: UseSubmitOptionsType<RequestType> = useSubmitDefaultOptions,
29
+ options?: UseSubmitOptionsType<RequestType>,
33
30
  ): UseSubmitReturnType<RequestType> => {
34
31
  // Build the configuration options
35
- const [globalConfig] = useConfigProvider();
32
+ const { config: globalConfig } = useProvider();
36
33
  const mergedOptions: UseSubmitOptionsType<RequestType> = useMemo(
37
34
  () => ({
38
35
  ...useSubmitDefaultOptions,
@@ -40,18 +37,18 @@ export const useSubmit = <RequestType extends RequestInstance>(
40
37
  ...options,
41
38
  }),
42
39
  // eslint-disable-next-line react-hooks/exhaustive-deps
43
- [globalConfig.useSubmitConfig, JSON.stringify(options), options.deepCompare],
40
+ [globalConfig.useSubmitConfig, JSON.stringify(options), options?.deepCompare],
44
41
  );
45
- const { disabled, dependencyTracking, initialData, bounce, bounceType, bounceTime, deepCompare } = mergedOptions;
42
+ const { disabled, dependencyTracking, initialResponse, bounce, bounceType, bounceTime, deepCompare } = mergedOptions;
46
43
 
47
44
  /**
48
- * Because of the dynamic cacheKey / queueKey signing within the request we need to store it's latest instance
45
+ * Because of the dynamic cacheKey / queryKey signing within the request we need to store it's latest instance
49
46
  * so the events got triggered properly and show the latest result without mixing it up
50
47
  */
51
48
  const { client } = request;
52
49
  const { cache, submitDispatcher: dispatcher, loggerManager } = client;
53
50
 
54
- const logger = useRef(loggerManager.init("useSubmit")).current;
51
+ const logger = useRef(loggerManager.initialize(client, "useSubmit")).current;
55
52
  const requestDebounce = useDebounce({ delay: bounceTime });
56
53
  const requestThrottle = useThrottle({
57
54
  interval: bounceTime,
@@ -59,7 +56,7 @@ export const useSubmit = <RequestType extends RequestInstance>(
59
56
  });
60
57
  const bounceResolver = useRef<
61
58
  (
62
- value: ResponseReturnType<
59
+ value: ResponseType<
63
60
  ExtractResponseType<RequestType>,
64
61
  ExtractErrorType<RequestType>,
65
62
  ExtractAdapterType<RequestType>
@@ -77,9 +74,9 @@ export const useSubmit = <RequestType extends RequestInstance>(
77
74
  logger,
78
75
  request,
79
76
  dispatcher,
80
- initialData,
81
- deepCompare,
82
- dependencyTracking,
77
+ initialResponse,
78
+ deepCompare: deepCompare as boolean,
79
+ dependencyTracking: dependencyTracking as boolean,
83
80
  });
84
81
 
85
82
  /**
@@ -101,46 +98,45 @@ export const useSubmit = <RequestType extends RequestInstance>(
101
98
  // ******************
102
99
 
103
100
  const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {
104
- const requestClone = request.clone(submitOptions as any) as RequestType;
101
+ const requestClone = request.clone(submitOptions as any) as unknown as RequestType;
105
102
 
106
103
  if (disabled) {
107
- logger.warning(`Cannot submit request`, { disabled, submitOptions });
104
+ logger.warning({ title: `Cannot submit request`, type: "system", extra: { disabled, submitOptions } });
108
105
  return Promise.resolve({
109
106
  data: null,
110
107
  error: new Error("Cannot submit request. Option 'disabled' is enabled"),
111
108
  status: null,
112
- extra: request.client.defaultExtra,
109
+ extra: request.client.adapter.defaultExtra,
113
110
  }) as Promise<
114
- ResponseReturnType<
115
- ExtractResponseType<RequestType>,
116
- ExtractErrorType<RequestType>,
117
- ExtractAdapterType<RequestType>
118
- >
111
+ ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>
119
112
  >;
120
113
  }
121
114
 
122
115
  const triggerRequest = () => {
123
116
  addCacheDataListener(requestClone);
124
- return sendRequest(requestClone, {
117
+
118
+ const configuration: RequestSendOptionsType<RequestType> = {
125
119
  dispatcherType: "submit",
126
- ...submitOptions,
127
- onSettle: (requestId, cmd) => {
128
- addLifecycleListeners(requestClone, requestId);
129
- submitOptions?.onSettle?.(requestId, cmd);
120
+ ...(submitOptions as RequestSendOptionsType<RequestType>),
121
+ onBeforeSent: (data) => {
122
+ addLifecycleListeners(requestClone, data.requestId);
123
+ submitOptions?.onBeforeSent?.(data);
130
124
  },
131
- });
125
+ };
126
+
127
+ return sendRequest(requestClone, configuration);
132
128
  };
133
129
 
134
- return new Promise<ExtractAdapterReturnType<RequestType>>((resolve) => {
130
+ return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {
135
131
  const performSubmit = async () => {
136
- logger.debug(`Submitting request`, { disabled, submitOptions });
132
+ logger.debug({ title: `Submitting request`, type: "system", extra: { disabled, submitOptions } });
137
133
  if (bounce) {
138
134
  const bouncedResolve = bounceResolver.current;
139
135
  // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.
140
136
  // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.
141
137
  // This way we can close previous promise, making sure our logic will not stuck in memory.
142
138
  bounceResolver.current = (
143
- value: ResponseReturnType<
139
+ value: ResponseType<
144
140
  ExtractResponseType<RequestType>,
145
141
  ExtractErrorType<RequestType>,
146
142
  ExtractAdapterType<RequestType>
@@ -175,22 +171,8 @@ export const useSubmit = <RequestType extends RequestInstance>(
175
171
  // Invalidation
176
172
  // ******************
177
173
 
178
- const handleInvalidation = (invalidateKey: InvalidationKeyType) => {
179
- if (invalidateKey && invalidateKey instanceof Request) {
180
- cache.invalidate(getRequestKey(invalidateKey));
181
- } else if (invalidateKey && !(invalidateKey instanceof Request)) {
182
- cache.invalidate(invalidateKey);
183
- }
184
- };
185
-
186
- const refetch = (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => {
187
- if (!invalidateKey) return;
188
-
189
- if (invalidateKey && Array.isArray(invalidateKey)) {
190
- invalidateKey.forEach(handleInvalidation);
191
- } else if (invalidateKey && !Array.isArray(invalidateKey)) {
192
- handleInvalidation(invalidateKey);
193
- }
174
+ const refetch = () => {
175
+ cache.invalidate(request);
194
176
  };
195
177
 
196
178
  // ******************
@@ -247,9 +229,13 @@ export const useSubmit = <RequestType extends RequestInstance>(
247
229
  setRenderKey("retries");
248
230
  return state.retries;
249
231
  },
250
- get timestamp() {
251
- setRenderKey("timestamp");
252
- return state.timestamp;
232
+ get responseTimestamp() {
233
+ setRenderKey("responseTimestamp");
234
+ return state.responseTimestamp;
235
+ },
236
+ get requestTimestamp() {
237
+ setRenderKey("requestTimestamp");
238
+ return state.requestTimestamp;
253
239
  },
254
240
  abort: callbacks.abort,
255
241
  ...actions,
@@ -1,4 +1,4 @@
1
- import { ExtractAdapterReturnType, NullableType, RequestInstance, RequestSendType } from "@hyper-fetch/core";
1
+ import { ExtractAdapterResolvedType, NullableType, RequestInstance, RequestSendType } from "@hyper-fetch/core";
2
2
 
3
3
  import { isEqual } from "utils";
4
4
  import {
@@ -10,7 +10,6 @@ import {
10
10
  UseTrackedStateType,
11
11
  UseTrackedStateActions,
12
12
  } from "helpers";
13
- import { InvalidationKeyType } from "types";
14
13
 
15
14
  export type UseSubmitOptionsType<T extends RequestInstance> = {
16
15
  /**
@@ -20,7 +19,7 @@ export type UseSubmitOptionsType<T extends RequestInstance> = {
20
19
  /**
21
20
  * If cache is empty we can use placeholder data.
22
21
  */
23
- initialData?: NullableType<Partial<ExtractAdapterReturnType<T>>>;
22
+ initialResponse?: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
24
23
  /**
25
24
  * Enable/disable debouncing for often changing keys or refreshing, to limit requests to server.
26
25
  */
@@ -66,7 +65,7 @@ export type UseSubmitReturnType<RequestType extends RequestInstance> = Omit<
66
65
  > &
67
66
  UseTrackedStateActions<RequestType> & {
68
67
  /**
69
- * Callback which allows to cancel ongoing requests from given queueKey.
68
+ * Callback which allows to cancel ongoing requests from given queryKey.
70
69
  */
71
70
  abort: () => void;
72
71
  /**
@@ -127,7 +126,7 @@ export type UseSubmitReturnType<RequestType extends RequestInstance> = Omit<
127
126
  reset: () => void;
128
127
  };
129
128
  /**
130
- * Refetch current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
129
+ * Refetch current request
131
130
  */
132
- refetch: (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => void;
131
+ refetch: () => void;
133
132
  };
package/src/index.ts CHANGED
@@ -4,9 +4,7 @@ export * from "./hooks/use-queue";
4
4
  export * from "./hooks/use-cache";
5
5
  export * from "./hooks/use-listener";
6
6
  export * from "./hooks/use-emitter";
7
- export * from "./hooks/use-event-messages";
8
7
  export * from "./hooks/use-app-manager";
9
8
  export * from "./helpers";
10
- export * from "./config-provider";
11
- export * from "./types";
9
+ export * from "./provider";
12
10
  export * from "./utils";
@@ -0,0 +1,2 @@
1
+ export * from "./provider";
2
+ export * from "./provider.types";
@@ -1,19 +1,22 @@
1
1
  import React, { useContext, useMemo, useState } from "react";
2
2
 
3
- import { ConfigProviderProps, ConfigProviderValueType } from "./config-provider.types";
3
+ import { ProviderProps, ProviderValueType } from "./provider.types";
4
4
 
5
- const ConfigContext = React.createContext<ConfigProviderValueType>([{}, () => null]);
5
+ const ConfigContext = React.createContext<ProviderValueType>({
6
+ config: {},
7
+ setConfig: () => null,
8
+ });
6
9
 
7
10
  /**
8
11
  * Context provider with configuration for hooks
9
12
  * @param options
10
13
  * @returns
11
14
  */
12
- export const ConfigProvider = ({ children, config }: ConfigProviderProps) => {
15
+ export const Provider = ({ children, config }: ProviderProps) => {
13
16
  const [currentConfig, setConfig] = useState(config || {});
14
17
 
15
18
  const value = useMemo(() => {
16
- const contextValue: ConfigProviderValueType = [currentConfig, setConfig];
19
+ const contextValue: ProviderValueType = { config: currentConfig, setConfig };
17
20
  return contextValue;
18
21
  }, [currentConfig]);
19
22
 
@@ -24,7 +27,7 @@ export const ConfigProvider = ({ children, config }: ConfigProviderProps) => {
24
27
  * Hook to allow reading current context config
25
28
  * @returns
26
29
  */
27
- export const useConfigProvider = (): ConfigProviderValueType => {
30
+ export const useProvider = (): ProviderValueType => {
28
31
  const config = useContext(ConfigContext);
29
32
  return config;
30
33
  };
@@ -1,27 +1,34 @@
1
- import React from "react";
2
1
  import { RequestInstance } from "@hyper-fetch/core";
2
+ import React from "react";
3
3
 
4
- import { UseFetchOptionsType } from "hooks/use-fetch";
5
4
  import { UseSubmitOptionsType } from "hooks/use-submit";
6
5
  import { UseCacheOptionsType } from "hooks/use-cache";
7
6
  import { UseQueueOptionsType } from "hooks/use-queue";
8
7
  import { UseListenerOptionsType } from "hooks/use-listener";
9
8
  import { UseEmitterOptionsType } from "hooks/use-emitter";
10
- import { UseEventMessagesOptionsType } from "hooks/use-event-messages";
9
+ import { UseFetchOptionsType } from "hooks/use-fetch";
11
10
 
12
- export type ConfigProviderOptionsType<SocketResponses = any> = {
11
+ export type ProviderOptionsType = {
13
12
  useFetchConfig?: Partial<UseFetchOptionsType<RequestInstance>>;
14
13
  useSubmitConfig?: Partial<UseSubmitOptionsType<RequestInstance>>;
15
14
  useCacheConfig?: Partial<UseCacheOptionsType<RequestInstance>>;
16
15
  useQueueConfig?: Partial<UseQueueOptionsType>;
17
16
  useListener?: Partial<UseListenerOptionsType>;
18
17
  useEmitter?: Partial<UseEmitterOptionsType>;
19
- useEventMessages?: Partial<UseEventMessagesOptionsType<SocketResponses>>;
20
18
  };
21
19
 
22
- export type ConfigProviderProps = {
20
+ export type ProviderProps = {
21
+ /**
22
+ * Children to render
23
+ */
23
24
  children: React.ReactNode;
24
- config?: ConfigProviderOptionsType;
25
+ /**
26
+ * Configuration to set for available hooks
27
+ */
28
+ config?: ProviderOptionsType;
25
29
  };
26
30
 
27
- export type ConfigProviderValueType = [ConfigProviderOptionsType, (newConfig: ConfigProviderOptionsType) => void];
31
+ export type ProviderValueType = {
32
+ config: ProviderOptionsType;
33
+ setConfig: (newConfig: ProviderOptionsType) => void;
34
+ };
@@ -17,6 +17,7 @@ export const isEmpty = (value: unknown): boolean => {
17
17
  * @returns true when elements are equal
18
18
  */
19
19
  export const isEqual = (firstValue: unknown, secondValue: unknown): boolean => {
20
+ // Nulls (objects), and other primitives
20
21
  if (firstValue === secondValue) return true;
21
22
 
22
23
  try {
@@ -32,9 +33,6 @@ export const isEqual = (firstValue: unknown, secondValue: unknown): boolean => {
32
33
  // Compared types are different
33
34
  if (firstValueType !== secondValueType) return false;
34
35
 
35
- // Null
36
- if (firstValue === null && secondValue === null) return true;
37
-
38
36
  // NaN
39
37
  if (isType("number") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) return true;
40
38
 
package/tsconfig.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "extends": "../../tsconfig.json",
3
3
  "compilerOptions": {
4
- "rootDir": ".",
4
+ "strict": true,
5
5
  "baseUrl": "./src",
6
6
  "jsx": "react-jsx"
7
7
  },
8
- "exclude": ["__tests__", "jest.config.ts"]
8
+ "exclude": ["node_modules", "dist", "jest.config.ts", "__tests__"]
9
9
  }