next-ws 0.2.6 → 0.2.7
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 +12 -10
- package/client/context.js +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -164,20 +164,21 @@ import { useCallback, useEffect, useState } from 'react';
|
|
|
164
164
|
|
|
165
165
|
export default function Page() {
|
|
166
166
|
const ws = useWebSocket();
|
|
167
|
-
//
|
|
167
|
+
// ^? WebSocket on the client, null on the server
|
|
168
168
|
|
|
169
169
|
const [value, setValue] = useState('');
|
|
170
|
-
const [message, setMessage] = useState<string | null>(
|
|
171
|
-
|
|
172
|
-
const onMessage = useCallback((event: MessageEvent) => {
|
|
173
|
-
const text = await event.data.text();
|
|
174
|
-
setMessage(text);
|
|
175
|
-
}, []);
|
|
170
|
+
const [message, setMessage] = useState<string | null>(null);
|
|
176
171
|
|
|
172
|
+
const onMessage = useCallback(
|
|
173
|
+
(event: MessageEvent<Blob>) =>
|
|
174
|
+
void event.data.text().then(setMessage),
|
|
175
|
+
[],
|
|
176
|
+
);
|
|
177
|
+
|
|
177
178
|
useEffect(() => {
|
|
178
179
|
ws?.addEventListener('message', onMessage);
|
|
179
180
|
return () => ws?.removeEventListener('message', onMessage);
|
|
180
|
-
}, [ws]);
|
|
181
|
+
}, [onMessage, ws]);
|
|
181
182
|
|
|
182
183
|
return <>
|
|
183
184
|
<input
|
|
@@ -186,15 +187,16 @@ export default function Page() {
|
|
|
186
187
|
onChange={event => setValue(event.target.value)}
|
|
187
188
|
/>
|
|
188
189
|
|
|
189
|
-
<button onClick={() => ws
|
|
190
|
+
<button onClick={() => ws?.send(value)}>
|
|
190
191
|
Send message to server
|
|
191
192
|
</button>
|
|
192
193
|
|
|
193
194
|
<p>
|
|
194
195
|
{message === null
|
|
195
|
-
? 'Waiting
|
|
196
|
+
? 'Waiting to receive message...'
|
|
196
197
|
: `Got message: ${message}`}
|
|
197
198
|
</p>
|
|
198
199
|
</>;
|
|
199
200
|
}
|
|
201
|
+
|
|
200
202
|
```
|
package/client/context.js
CHANGED
|
@@ -22,7 +22,9 @@ function WebSocketProvider({ children, url, protocols, binaryType, }) {
|
|
|
22
22
|
return client;
|
|
23
23
|
}, [isBrowser, url, protocols]);
|
|
24
24
|
(0, react_1.useEffect)(() => {
|
|
25
|
-
|
|
25
|
+
if (instance?.readyState !== WebSocket.OPEN)
|
|
26
|
+
return;
|
|
27
|
+
return () => instance.close();
|
|
26
28
|
}, []);
|
|
27
29
|
return (0, jsx_runtime_1.jsx)(exports.WebSocketContext.Provider, { value: instance, children: children });
|
|
28
30
|
}
|