@hyper-fetch/react 1.7.0 → 2.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.
Files changed (56) hide show
  1. package/README.md +4 -3
  2. package/dist/config-provider/config-provider.types.d.ts +7 -7
  3. package/dist/helpers/index.d.ts +1 -0
  4. package/dist/helpers/use-command-events/use-command-events.hooks.d.ts +2 -3
  5. package/dist/helpers/use-command-events/use-command-events.types.d.ts +12 -12
  6. package/dist/helpers/use-socket-state/index.d.ts +3 -0
  7. package/dist/helpers/use-socket-state/use-socket-state.constants.d.ts +2 -0
  8. package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +16 -0
  9. package/dist/helpers/use-socket-state/use-socket-state.types.d.ts +9 -0
  10. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts +1 -2
  11. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts +5 -5
  12. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +5 -5
  13. package/dist/hooks/use-app-manager/use-app-manager.hooks.d.ts +2 -3
  14. package/dist/hooks/use-app-manager/use-app-manager.types.d.ts +1 -1
  15. package/dist/hooks/use-cache/use-cache.hooks.d.ts +2 -3
  16. package/dist/hooks/use-cache/use-cache.types.d.ts +4 -4
  17. package/dist/hooks/use-emitter/index.d.ts +2 -0
  18. package/dist/hooks/use-emitter/use-emitter.hooks.d.ts +19 -0
  19. package/dist/hooks/use-emitter/use-emitter.types.d.ts +3 -0
  20. package/dist/hooks/use-event-messages/index.d.ts +2 -0
  21. package/dist/hooks/use-event-messages/use-event-messages.hooks.d.ts +24 -0
  22. package/dist/hooks/use-event-messages/use-event-messages.types.d.ts +4 -0
  23. package/dist/hooks/use-fetch/use-fetch.constants.d.ts +2 -2
  24. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts +2 -3
  25. package/dist/hooks/use-fetch/use-fetch.types.d.ts +5 -5
  26. package/dist/hooks/use-listener/index.d.ts +2 -0
  27. package/dist/hooks/use-listener/use-listener.hooks.d.ts +20 -0
  28. package/dist/hooks/use-listener/use-listener.types.d.ts +3 -0
  29. package/dist/hooks/use-queue/use-queue.constants.d.ts +1 -1
  30. package/dist/hooks/use-queue/use-queue.hooks.d.ts +2 -3
  31. package/dist/hooks/use-queue/use-queue.types.d.ts +3 -3
  32. package/dist/hooks/use-submit/use-submit.constants.d.ts +1 -1
  33. package/dist/hooks/use-submit/use-submit.hooks.d.ts +2 -3
  34. package/dist/hooks/use-submit/use-submit.types.d.ts +14 -14
  35. package/dist/index.cjs.js +1 -1
  36. package/dist/index.cjs.js.map +4 -4
  37. package/dist/index.esm.js +1 -1
  38. package/dist/index.esm.js.map +4 -4
  39. package/dist/types/invalidation.types.d.ts +1 -1
  40. package/package.json +11 -3
  41. package/src/helpers/index.ts +1 -0
  42. package/src/helpers/use-socket-state/index.ts +3 -0
  43. package/src/helpers/use-socket-state/use-socket-state.constants.ts +8 -0
  44. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +135 -0
  45. package/src/helpers/use-socket-state/use-socket-state.types.ts +10 -0
  46. package/src/hooks/use-emitter/index.ts +2 -0
  47. package/src/hooks/use-emitter/use-emitter.hooks.ts +47 -0
  48. package/src/hooks/use-emitter/use-emitter.types.ts +3 -0
  49. package/src/hooks/use-event-messages/index.ts +2 -0
  50. package/src/hooks/use-event-messages/use-event-messages.hooks.ts +65 -0
  51. package/src/hooks/use-event-messages/use-event-messages.types.ts +4 -0
  52. package/src/hooks/use-listener/index.ts +2 -0
  53. package/src/hooks/use-listener/use-listener.hooks.ts +75 -0
  54. package/src/hooks/use-listener/use-listener.types.ts +3 -0
  55. package/src/hooks/use-submit/use-submit.hooks.ts +18 -14
  56. package/src/hooks/use-submit/use-submit.types.ts +14 -17
@@ -0,0 +1,47 @@
1
+ import { useRef } from "react";
2
+ import { EmitterInstance } from "@hyper-fetch/sockets";
3
+
4
+ import { UseEmitterOptionsType } from "hooks/use-emitter";
5
+ import { useSocketState } from "helpers";
6
+
7
+ // Todo bounce
8
+
9
+ export const useEmitter = <EmitterType extends EmitterInstance>(
10
+ emitter: EmitterType,
11
+ { dependencyTracking }: UseEmitterOptionsType,
12
+ ) => {
13
+ const onEmitCallback = useRef<null | ((emitter: EmitterType) => void)>(null);
14
+ const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });
15
+
16
+ const additionalCallbacks = {
17
+ onEmit: (callback: (emitter: EmitterType) => void) => {
18
+ onEmitCallback.current = callback;
19
+ },
20
+ };
21
+
22
+ const emit: typeof emitter.emit = (...args) => {
23
+ actions.setTimestamp(+new Date());
24
+ onEmitCallback.current?.(emitter);
25
+ return emitter.emit(...args);
26
+ };
27
+
28
+ return {
29
+ get connected() {
30
+ setRenderKey("connected");
31
+ return state.connected;
32
+ },
33
+ get connecting() {
34
+ setRenderKey("connecting");
35
+ return state.connecting;
36
+ },
37
+ get timestamp() {
38
+ setRenderKey("timestamp");
39
+ return state.timestamp;
40
+ },
41
+ ...actions,
42
+ ...callbacks,
43
+ ...additionalCallbacks,
44
+ emit,
45
+ reconnect: emitter.socket.reconnect,
46
+ };
47
+ };
@@ -0,0 +1,3 @@
1
+ export type UseEmitterOptionsType = {
2
+ dependencyTracking?: boolean;
3
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./use-event-messages.hooks";
2
+ export * from "./use-event-messages.types";
@@ -0,0 +1,65 @@
1
+ import { useRef } from "react";
2
+ import { useDidUpdate } from "@better-typed/react-lifecycle-hooks";
3
+ import { SocketInstance } from "@hyper-fetch/sockets";
4
+
5
+ import { useSocketState } from "helpers";
6
+ import { UseEventMessagesOptionsType } from "hooks/use-event-messages";
7
+
8
+ /**
9
+ * Allow to listen to all event messages received with sockets
10
+ * @param socket
11
+ * @param options
12
+ * @returns
13
+ */
14
+ export const useEventMessages = <ResponsesType>(
15
+ socket: SocketInstance,
16
+ { dependencyTracking = false, filter }: UseEventMessagesOptionsType<ResponsesType>,
17
+ ) => {
18
+ const onEventCallback = useRef<null | ((data: ResponsesType, event: MessageEvent<ResponsesType>) => void)>(null);
19
+ const [state, actions, callbacks, { setRenderKey }] = useSocketState(socket, { dependencyTracking });
20
+
21
+ useDidUpdate(
22
+ () => {
23
+ const unmountListener = socket.events.onListenerEvent((data, event) => {
24
+ const filterFn = typeof filter === "function" ? () => filter(data, event) : () => filter.includes(data.name);
25
+ const isFiltered = filter ? filterFn() : false;
26
+ if (!isFiltered) {
27
+ onEventCallback.current?.(data, event);
28
+ actions.setData(data);
29
+ actions.setTimestamp(+new Date());
30
+ }
31
+ });
32
+ return unmountListener;
33
+ },
34
+ [socket, filter],
35
+ true,
36
+ );
37
+
38
+ const additionalCallbacks = {
39
+ onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {
40
+ onEventCallback.current = callback;
41
+ },
42
+ };
43
+
44
+ return {
45
+ get data() {
46
+ setRenderKey("data");
47
+ return state.data;
48
+ },
49
+ get connected() {
50
+ setRenderKey("connected");
51
+ return state.connected;
52
+ },
53
+ get connecting() {
54
+ setRenderKey("connecting");
55
+ return state.connecting;
56
+ },
57
+ get timestamp() {
58
+ setRenderKey("timestamp");
59
+ return state.timestamp;
60
+ },
61
+ ...actions,
62
+ ...callbacks,
63
+ ...additionalCallbacks,
64
+ };
65
+ };
@@ -0,0 +1,4 @@
1
+ export type UseEventMessagesOptionsType<ResponsesType> = {
2
+ dependencyTracking?: boolean;
3
+ filter?: ((data: ResponsesType, event: MessageEvent<ResponsesType>) => boolean) | string[];
4
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./use-listener.hooks";
2
+ export * from "./use-listener.types";
@@ -0,0 +1,75 @@
1
+ import { useRef } from "react";
2
+ import { useDidUpdate, useWillUnmount } from "@better-typed/react-lifecycle-hooks";
3
+ import { ListenerInstance, ExtractListenerDataType } from "@hyper-fetch/sockets";
4
+
5
+ import { useSocketState } from "helpers";
6
+ import { UseListenerOptionsType } from "hooks/use-listener";
7
+
8
+ export const useListener = <ListenerType extends ListenerInstance>(
9
+ listener: ListenerType,
10
+ { dependencyTracking }: UseListenerOptionsType,
11
+ ) => {
12
+ const onEventCallback = useRef<
13
+ | null
14
+ | ((
15
+ data: ExtractListenerDataType<ListenerType>,
16
+ event: MessageEvent<ExtractListenerDataType<ListenerType>>,
17
+ ) => void)
18
+ >(null);
19
+ const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);
20
+ const [state, actions, callbacks, { setRenderKey }] = useSocketState(listener.socket, { dependencyTracking });
21
+
22
+ const stopListener = () => {
23
+ removeListenerRef.current?.[0]();
24
+ };
25
+
26
+ const listen = () => {
27
+ stopListener();
28
+ removeListenerRef.current = listener.listen((data, event) => {
29
+ onEventCallback.current?.(data, event);
30
+ actions.setData(data);
31
+ actions.setTimestamp(+new Date());
32
+ });
33
+ };
34
+
35
+ useDidUpdate(
36
+ () => {
37
+ listen();
38
+ },
39
+ [listener],
40
+ true,
41
+ );
42
+
43
+ useWillUnmount(() => {
44
+ stopListener();
45
+ });
46
+
47
+ const additionalCallbacks = {
48
+ onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {
49
+ onEventCallback.current = callback;
50
+ },
51
+ };
52
+
53
+ return {
54
+ get data() {
55
+ setRenderKey("data");
56
+ return state.data;
57
+ },
58
+ get connected() {
59
+ setRenderKey("connected");
60
+ return state.connected;
61
+ },
62
+ get connecting() {
63
+ setRenderKey("connecting");
64
+ return state.connecting;
65
+ },
66
+ get timestamp() {
67
+ setRenderKey("timestamp");
68
+ return state.timestamp;
69
+ },
70
+ ...actions,
71
+ ...callbacks,
72
+ ...additionalCallbacks,
73
+ listen,
74
+ };
75
+ };
@@ -0,0 +1,3 @@
1
+ export type UseListenerOptionsType = {
2
+ dependencyTracking?: boolean;
3
+ };
@@ -9,6 +9,7 @@ import {
9
9
  ExtractResponse,
10
10
  ExtractError,
11
11
  FetchType,
12
+ FetchMethodType,
12
13
  } from "@hyper-fetch/core";
13
14
  import { useDidMount } from "@better-typed/react-lifecycle-hooks";
14
15
  import { useDebounce, useThrottle } from "@better-typed/react-performance-hooks";
@@ -25,10 +26,10 @@ import { InvalidationKeyType } from "types";
25
26
  * @param options
26
27
  * @returns
27
28
  */
28
- export const useSubmit = <Command extends CommandInstance>(
29
- command: Command,
30
- options: UseSubmitOptionsType<Command> = useSubmitDefaultOptions,
31
- ): UseSubmitReturnType<Command> => {
29
+ export const useSubmit = <CommandType extends CommandInstance>(
30
+ command: CommandType,
31
+ options: UseSubmitOptionsType<CommandType> = useSubmitDefaultOptions,
32
+ ): UseSubmitReturnType<CommandType> => {
32
33
  // Build the configuration options
33
34
  const [globalConfig] = useConfigProvider();
34
35
  const mergedOptions = useMemo(
@@ -51,9 +52,9 @@ export const useSubmit = <Command extends CommandInstance>(
51
52
  const logger = useRef(loggerManager.init("useSubmit")).current;
52
53
  const requestDebounce = useDebounce(bounceTime);
53
54
  const requestThrottle = useThrottle(bounceTime);
54
- const bounceResolver = useRef<(value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => void>(
55
- () => null,
56
- );
55
+ const bounceResolver = useRef<
56
+ (value: ClientResponseType<ExtractResponse<CommandType>, ExtractError<CommandType>>) => void
57
+ >(() => null);
57
58
 
58
59
  const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
59
60
  const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
@@ -61,7 +62,7 @@ export const useSubmit = <Command extends CommandInstance>(
61
62
  /**
62
63
  * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
63
64
  */
64
- const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<Command>({
65
+ const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<CommandType>({
65
66
  logger,
66
67
  command,
67
68
  dispatcher,
@@ -87,13 +88,14 @@ export const useSubmit = <Command extends CommandInstance>(
87
88
  // Submitting
88
89
  // ******************
89
90
 
90
- const handleSubmit = (...parameters: Parameters<Command["send"]>) => {
91
- const submitOptions = parameters[0] as FetchType<Command> | undefined;
92
- const commandClone = command.clone(submitOptions as any) as Command;
91
+ const handleSubmit: FetchMethodType<CommandType> = (submitOptions?: FetchType<CommandType>) => {
92
+ const commandClone = command.clone(submitOptions as any) as CommandType;
93
93
 
94
94
  if (disabled) {
95
95
  logger.warning(`Cannot submit request`, { disabled, submitOptions });
96
- throw new Error("Cannot submit request. Option 'disabled' is enabled");
96
+ return Promise.resolve([null, new Error("Cannot submit request. Option 'disabled' is enabled"), 0]) as Promise<
97
+ ClientResponseType<ExtractResponse<CommandType>, ExtractError<CommandType>>
98
+ >;
97
99
  }
98
100
 
99
101
  const triggerRequest = () => {
@@ -108,7 +110,7 @@ export const useSubmit = <Command extends CommandInstance>(
108
110
  });
109
111
  };
110
112
 
111
- return new Promise<ExtractClientReturnType<Command>>((resolve) => {
113
+ return new Promise<ExtractClientReturnType<CommandType>>((resolve) => {
112
114
  const performSubmit = async () => {
113
115
  logger.debug(`Submitting request`, { disabled, submitOptions });
114
116
  if (bounce) {
@@ -116,7 +118,9 @@ export const useSubmit = <Command extends CommandInstance>(
116
118
  // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.
117
119
  // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.
118
120
  // This way we can close previous promise, making sure our logic will not stuck in memory.
119
- bounceResolver.current = (value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => {
121
+ bounceResolver.current = (
122
+ value: ClientResponseType<ExtractResponse<CommandType>, ExtractError<CommandType>>,
123
+ ) => {
120
124
  // Trigger previous awaiting calls to resolve together in bounced batches
121
125
  bouncedResolve(value);
122
126
  resolve(value);
@@ -1,10 +1,4 @@
1
- import {
2
- CacheValueType,
3
- ExtractError,
4
- ExtractResponse,
5
- CommandInstance,
6
- ExtractClientReturnType,
7
- } from "@hyper-fetch/core";
1
+ import { CacheValueType, ExtractError, ExtractResponse, CommandInstance, FetchMethodType } from "@hyper-fetch/core";
8
2
 
9
3
  import { isEqual } from "utils";
10
4
  import {
@@ -49,8 +43,11 @@ export type UseSubmitOptionsType<T extends CommandInstance> = {
49
43
  deepCompare?: boolean | typeof isEqual;
50
44
  };
51
45
 
52
- export type UseSubmitReturnType<T extends CommandInstance> = Omit<UseTrackedStateType<T>, "loading"> &
53
- UseTrackedStateActions<T> & {
46
+ export type UseSubmitReturnType<CommandType extends CommandInstance> = Omit<
47
+ UseTrackedStateType<CommandType>,
48
+ "loading"
49
+ > &
50
+ UseTrackedStateActions<CommandType> & {
54
51
  /**
55
52
  * Callback which allows to cancel ongoing requests from given queueKey.
56
53
  */
@@ -58,23 +55,23 @@ export type UseSubmitReturnType<T extends CommandInstance> = Omit<UseTrackedStat
58
55
  /**
59
56
  * Helper hook listening on success response.
60
57
  */
61
- onSubmitSuccess: (callback: OnSuccessCallbackType<T>) => void;
58
+ onSubmitSuccess: (callback: OnSuccessCallbackType<CommandType>) => void;
62
59
  /**
63
60
  * Helper hook listening on error response.
64
61
  */
65
- onSubmitError: (callback: OnErrorCallbackType<T>) => void;
62
+ onSubmitError: (callback: OnErrorCallbackType<CommandType>) => void;
66
63
  /**
67
64
  * Helper hook listening on any response.
68
65
  */
69
- onSubmitFinished: (callback: OnFinishedCallbackType<T>) => void;
66
+ onSubmitFinished: (callback: OnFinishedCallbackType<CommandType>) => void;
70
67
  /**
71
68
  * Helper hook listening on request start.
72
69
  */
73
- onSubmitRequestStart: (callback: OnStartCallbackType<T>) => void;
70
+ onSubmitRequestStart: (callback: OnStartCallbackType<CommandType>) => void;
74
71
  /**
75
72
  * Helper hook listening on response start(before we receive all data from server).
76
73
  */
77
- onSubmitResponseStart: (callback: OnStartCallbackType<T>) => void;
74
+ onSubmitResponseStart: (callback: OnStartCallbackType<CommandType>) => void;
78
75
  /**
79
76
  * Helper hook listening on download progress ETA. We can later match given requests by their id's or command instance which holds all data which is being transferred.
80
77
  */
@@ -86,15 +83,15 @@ export type UseSubmitReturnType<T extends CommandInstance> = Omit<UseTrackedStat
86
83
  /**
87
84
  * Helper hook listening on aborting of requests. Abort events are not triggering onError callbacks.
88
85
  */
89
- onSubmitAbort: (callback: OnErrorCallbackType<T>) => void;
86
+ onSubmitAbort: (callback: OnErrorCallbackType<CommandType>) => void;
90
87
  /**
91
88
  * Helper hook listening on request going into offline awaiting for network connection to be restored. It will not trigger onError when 'offline' mode is set on command.
92
89
  */
93
- onSubmitOfflineError: (callback: OnErrorCallbackType<T>) => void;
90
+ onSubmitOfflineError: (callback: OnErrorCallbackType<CommandType>) => void;
94
91
  /**
95
92
  * Method responsible for triggering requests. It return Promise which will be resolved with the request.
96
93
  */
97
- submit: (...parameters: Parameters<T["send"]>) => Promise<ExtractClientReturnType<T>>;
94
+ submit: FetchMethodType<CommandType>;
98
95
  /**
99
96
  * Request loading state
100
97
  */