@hyper-fetch/react 9.8.1 → 10.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/README.md +24 -26
- package/__tests__/features/use-listener/use-listener.payload.spec.tsx +196 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +22 -1
- package/__tests__/features/use-listener/use-listener.status.spec.tsx +288 -0
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +10 -3
- package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts +20 -4
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.types.d.ts +11 -0
- package/dist/hooks/use-listener/use-listener.types.d.ts.map +1 -1
- package/dist/index.mjs +66 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-socket-state/use-socket-state.hooks.ts +36 -11
- package/src/hooks/use-listener/use-listener.hooks.ts +66 -13
- package/src/hooks/use-listener/use-listener.types.ts +12 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "10.0.0",
|
|
4
4
|
"description": "React hooks and utils for the hyper-fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
@@ -3,10 +3,20 @@ import type { SocketInstance, ExtractSocketExtraType } from "@hyper-fetch/socket
|
|
|
3
3
|
import type { UseSocketStateType, UseSocketStateProps } from "helpers";
|
|
4
4
|
import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Tracked socket state shared by the socket hooks. `extendedState` adds hook-specific fields (e.g. the listener
|
|
8
|
+
* status) that are tracked the same way and changed with `actions.setExtendedState`.
|
|
9
|
+
*/
|
|
10
|
+
export const useSocketState = <
|
|
11
|
+
DataType,
|
|
12
|
+
Socket extends SocketInstance,
|
|
13
|
+
ExtendedState extends Record<string, unknown> = Record<never, never>,
|
|
14
|
+
>(
|
|
7
15
|
socket: Socket,
|
|
8
|
-
{ dependencyTracking }: UseSocketStateProps,
|
|
16
|
+
{ dependencyTracking, extendedState }: UseSocketStateProps & { extendedState?: ExtendedState },
|
|
9
17
|
) => {
|
|
18
|
+
type StateType = UseSocketStateType<Socket, DataType> & ExtendedState;
|
|
19
|
+
const initialExtendedState = useRef(extendedState);
|
|
10
20
|
const onDisconnectCallback = useRef<null | VoidFunction>(null);
|
|
11
21
|
const onErrorCallback = useRef<null | ((event: any) => void)>(null);
|
|
12
22
|
const onConnectedCallback = useRef<null | VoidFunction>(null);
|
|
@@ -14,14 +24,15 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
|
|
|
14
24
|
const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
|
|
15
25
|
const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
|
|
16
26
|
|
|
17
|
-
const state = useRef<
|
|
27
|
+
const state = useRef<StateType>({
|
|
28
|
+
...initialExtendedState.current,
|
|
18
29
|
data: null,
|
|
19
30
|
extra: null,
|
|
20
31
|
connected: socket.adapter.connected,
|
|
21
32
|
connecting: socket.adapter.connecting,
|
|
22
33
|
timestamp: null,
|
|
23
|
-
});
|
|
24
|
-
const renderKeys = useRef<(keyof
|
|
34
|
+
} as StateType);
|
|
35
|
+
const renderKeys = useRef<(keyof StateType)[]>([]);
|
|
25
36
|
|
|
26
37
|
// ******************
|
|
27
38
|
// useSyncExternalStore
|
|
@@ -50,12 +61,14 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
|
|
|
50
61
|
// Dependency Tracking
|
|
51
62
|
// ******************
|
|
52
63
|
|
|
53
|
-
const renderKeyTrigger = (keys: (keyof
|
|
64
|
+
const renderKeyTrigger = (keys: (keyof StateType)[]) => {
|
|
54
65
|
const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
|
|
55
|
-
if (shouldRerender) {
|
|
66
|
+
if (shouldRerender) {
|
|
67
|
+
emitChange();
|
|
68
|
+
}
|
|
56
69
|
};
|
|
57
70
|
|
|
58
|
-
const setRenderKey = (renderKey: keyof
|
|
71
|
+
const setRenderKey = (renderKey: keyof StateType) => {
|
|
59
72
|
if (!renderKeys.current.includes(renderKey)) {
|
|
60
73
|
renderKeys.current.push(renderKey);
|
|
61
74
|
}
|
|
@@ -106,13 +119,14 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
|
|
|
106
119
|
},
|
|
107
120
|
clearState: () => {
|
|
108
121
|
state.current = {
|
|
122
|
+
...initialExtendedState.current,
|
|
109
123
|
data: null,
|
|
110
124
|
extra: null,
|
|
111
125
|
connected: false,
|
|
112
126
|
connecting: false,
|
|
113
127
|
timestamp: null,
|
|
114
|
-
};
|
|
115
|
-
renderKeyTrigger(Object.keys(state.current) as (keyof
|
|
128
|
+
} as StateType;
|
|
129
|
+
renderKeyTrigger(Object.keys(state.current) as (keyof StateType)[]);
|
|
116
130
|
},
|
|
117
131
|
};
|
|
118
132
|
|
|
@@ -187,5 +201,16 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
|
|
|
187
201
|
|
|
188
202
|
const getState = () => state.current;
|
|
189
203
|
|
|
190
|
-
|
|
204
|
+
/** Changes the hook-specific fields added with `extendedState` */
|
|
205
|
+
const setExtendedState = (newState: Partial<ExtendedState>) => {
|
|
206
|
+
Object.assign(state.current, newState);
|
|
207
|
+
renderKeyTrigger(Object.keys(newState) as (keyof StateType)[]);
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
return [
|
|
211
|
+
state.current,
|
|
212
|
+
actions,
|
|
213
|
+
callbacks,
|
|
214
|
+
{ setRenderKey, getState, rerender: emitChange, setExtendedState },
|
|
215
|
+
] as const;
|
|
191
216
|
};
|
|
@@ -1,28 +1,44 @@
|
|
|
1
1
|
import { useDidUpdate, useWillUnmount } from "@better-hooks/lifecycle";
|
|
2
|
-
import { replaceEqualDeep } from "@hyper-fetch/core";
|
|
3
|
-
import type {
|
|
2
|
+
import { replaceEqualDeep, stringifyKey } from "@hyper-fetch/core";
|
|
3
|
+
import type {
|
|
4
|
+
ExtractListenerDeliveredType,
|
|
5
|
+
ListenerEndType,
|
|
6
|
+
ListenerInstance,
|
|
7
|
+
ListenerLifecycleOptionsType,
|
|
8
|
+
ListenerRequiresPayload,
|
|
9
|
+
} from "@hyper-fetch/sockets";
|
|
4
10
|
import { getDeliveryKey } from "@hyper-fetch/sockets";
|
|
5
11
|
import { useSocketState } from "helpers";
|
|
6
|
-
import type { UseListenerOptionsType } from "hooks/use-listener";
|
|
12
|
+
import type { ListenerStatusType, UseListenerOptionsType } from "hooks/use-listener";
|
|
7
13
|
import { useProvider } from "provider";
|
|
8
14
|
import { useRef } from "react";
|
|
9
15
|
import { createTrackedProxy } from "utils";
|
|
10
16
|
|
|
11
|
-
/**
|
|
17
|
+
/** A listener whose subscription payload is required has to get it with `setPayload()` before it is passed */
|
|
18
|
+
type ListenerWithPayloadType<ListenerType extends ListenerInstance> =
|
|
19
|
+
ListenerRequiresPayload<ListenerType> extends true
|
|
20
|
+
? ListenerType & { "Set the payload with setPayload() before passing the listener": never }
|
|
21
|
+
: ListenerType;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks.
|
|
25
|
+
* Changing the topic params, payload, options, delivery or socket of the listener starts a new subscription.
|
|
26
|
+
*/
|
|
12
27
|
export const useListener = <
|
|
13
28
|
ListenerType extends ListenerInstance,
|
|
14
29
|
TSelected = ExtractListenerDeliveredType<ListenerType>,
|
|
15
30
|
>(
|
|
16
|
-
listener: ListenerType
|
|
31
|
+
listener: ListenerWithPayloadType<ListenerType>,
|
|
17
32
|
options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>,
|
|
18
33
|
) => {
|
|
19
34
|
const { config: globalConfig } = useProvider();
|
|
20
35
|
const { dependencyTracking = true, structuralSharing = true } = { ...globalConfig.useListener, ...options };
|
|
21
36
|
const select = options?.select;
|
|
22
|
-
const [state, actions, callbacks, { setRenderKey, getState, rerender }] = useSocketState<
|
|
37
|
+
const [state, actions, callbacks, { setRenderKey, getState, rerender, setExtendedState }] = useSocketState<
|
|
23
38
|
TSelected,
|
|
24
|
-
ListenerType["socket"]
|
|
25
|
-
|
|
39
|
+
ListenerType["socket"],
|
|
40
|
+
{ status: ListenerStatusType; error: Error | null }
|
|
41
|
+
>(listener.socket, { dependencyTracking, extendedState: { status: "idle", error: null } });
|
|
26
42
|
const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);
|
|
27
43
|
|
|
28
44
|
/**
|
|
@@ -66,6 +82,8 @@ export const useListener = <
|
|
|
66
82
|
const onEventCallback = useRef<
|
|
67
83
|
null | ((response: { data: ExtractListenerDeliveredType<ListenerType>; extra: Record<string, any> }) => void)
|
|
68
84
|
>(null);
|
|
85
|
+
const onStartCallback = useRef<null | ((data: { topic: string }) => void)>(null);
|
|
86
|
+
const onEndCallback = useRef<null | ((data: ListenerEndType) => void)>(null);
|
|
69
87
|
|
|
70
88
|
/**
|
|
71
89
|
* Actions
|
|
@@ -77,7 +95,25 @@ export const useListener = <
|
|
|
77
95
|
|
|
78
96
|
const listen = () => {
|
|
79
97
|
stopListener();
|
|
80
|
-
|
|
98
|
+
// Set before subscribing - adapters without confirmation start the subscription synchronously
|
|
99
|
+
setExtendedState({ status: "starting", error: null });
|
|
100
|
+
const lifecycle = {
|
|
101
|
+
onStart: (data: { topic: string }) => {
|
|
102
|
+
setExtendedState({ status: "listening" });
|
|
103
|
+
onStartCallback.current?.(data);
|
|
104
|
+
},
|
|
105
|
+
onEnd: (data: ListenerEndType) => {
|
|
106
|
+
removeListenerRef.current = null;
|
|
107
|
+
setExtendedState({ status: data.error ? "failed" : "ended", error: data.error });
|
|
108
|
+
onEndCallback.current?.(data);
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
// The payload is set on the listener, so only the lifecycle callbacks are passed
|
|
112
|
+
const listenWithLifecycle = listener.listen as (
|
|
113
|
+
callback: Parameters<typeof listener.listen>[0],
|
|
114
|
+
options: ListenerLifecycleOptionsType,
|
|
115
|
+
) => VoidFunction;
|
|
116
|
+
removeListenerRef.current = listenWithLifecycle(({ data, extra }) => {
|
|
81
117
|
onEventCallback.current?.({ data, extra });
|
|
82
118
|
rawData.current = { data };
|
|
83
119
|
appliedSelect.current = selectRef.current;
|
|
@@ -98,13 +134,21 @@ export const useListener = <
|
|
|
98
134
|
}
|
|
99
135
|
actions.setExtra(extra);
|
|
100
136
|
actions.setTimestamp(Date.now());
|
|
101
|
-
});
|
|
137
|
+
}, lifecycle);
|
|
102
138
|
};
|
|
103
139
|
|
|
104
140
|
const additionalCallbacks = {
|
|
105
141
|
onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {
|
|
106
142
|
onEventCallback.current = callback;
|
|
107
143
|
},
|
|
144
|
+
/** The subscription started - with tRPC and oRPC when the server confirmed it, also after a reconnect */
|
|
145
|
+
onStart: (callback: NonNullable<typeof onStartCallback.current>) => {
|
|
146
|
+
onStartCallback.current = callback;
|
|
147
|
+
},
|
|
148
|
+
/** The server ended the subscription, with `error` when it failed */
|
|
149
|
+
onEnd: (callback: NonNullable<typeof onEndCallback.current>) => {
|
|
150
|
+
onEndCallback.current = callback;
|
|
151
|
+
},
|
|
108
152
|
};
|
|
109
153
|
|
|
110
154
|
/**
|
|
@@ -116,8 +160,15 @@ export const useListener = <
|
|
|
116
160
|
listen();
|
|
117
161
|
},
|
|
118
162
|
// Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.
|
|
119
|
-
// The socket is a dependency too - the same topic on another socket is a different subscription
|
|
120
|
-
|
|
163
|
+
// The socket is a dependency too - the same topic on another socket is a different subscription, the same
|
|
164
|
+
// goes for the payload - the same procedure with another input is another subscription.
|
|
165
|
+
[
|
|
166
|
+
listener.socket,
|
|
167
|
+
listener.topic,
|
|
168
|
+
stringifyKey(listener.payload),
|
|
169
|
+
JSON.stringify(listener.options),
|
|
170
|
+
getDeliveryKey(listener.delivery),
|
|
171
|
+
],
|
|
121
172
|
true,
|
|
122
173
|
);
|
|
123
174
|
|
|
@@ -125,7 +176,7 @@ export const useListener = <
|
|
|
125
176
|
stopListener();
|
|
126
177
|
});
|
|
127
178
|
|
|
128
|
-
const trackedKeys = ["data", "extra", "connected", "connecting", "timestamp"] as const;
|
|
179
|
+
const trackedKeys = ["data", "extra", "connected", "connecting", "timestamp", "status", "error"] as const;
|
|
129
180
|
|
|
130
181
|
return createTrackedProxy(
|
|
131
182
|
{
|
|
@@ -134,6 +185,8 @@ export const useListener = <
|
|
|
134
185
|
connected: state.connected,
|
|
135
186
|
connecting: state.connecting,
|
|
136
187
|
timestamp: state.timestamp,
|
|
188
|
+
status: state.status,
|
|
189
|
+
error: state.error,
|
|
137
190
|
...actions,
|
|
138
191
|
...callbacks,
|
|
139
192
|
...additionalCallbacks,
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the subscription of `useListener` is:
|
|
3
|
+
* - `idle` - not listening yet (e.g. during server rendering)
|
|
4
|
+
* - `starting` - subscribed, waiting for the server to confirm it (tRPC, oRPC)
|
|
5
|
+
* - `listening` - messages can arrive. Adapters without confirmation get here right after subscribing
|
|
6
|
+
* - `ended` - the server finished the subscription
|
|
7
|
+
* - `failed` - the server ended the subscription with an error, see `error`
|
|
8
|
+
*
|
|
9
|
+
* After `ended` or `failed` the hook stays unsubscribed until `listen()` is called or the listener changes.
|
|
10
|
+
*/
|
|
11
|
+
export type ListenerStatusType = "idle" | "starting" | "listening" | "ended" | "failed";
|
|
12
|
+
|
|
1
13
|
export type UseListenerOptionsType<DataType = any, TSelected = DataType> = {
|
|
2
14
|
/** When true (default), only re-renders when accessed state properties change */
|
|
3
15
|
dependencyTracking?: boolean;
|