Comments (6)
I apologize for letting this slip through the cracks. I was away for much of the month of November, and assumed the issue resolved when it was closed.
I don't mind the idea of exposing errors through the hook interface, similar to lastMessage and in addition to the callback option, but wonder if this would even be better than the approach that @florianbepunkt eventually took (which I think is reasonable) -- when/whether to clear lastError
depends on circumstances/use-cases that might be beyond the scope of the library, and ultimately can be achieved quite easily with a custom hook around useWebSocket:
const customUseWebSocket = (
url: string,
options: Options,
connect: boolean,
): ReturnType<typeof useWebSocket> & { lastError: Error } => {
const [lastError, setLastError] = useState<Error>(null);
const useWebSocketReturnValue = useWebSocket(url, {
...options,
onError: setLastError,
}, connect);
return {
...useWebSocketReturnValue,
lastError,
};
};
You can replace the useState with useRef if you don't want the error to force a redundant component update.
Ultimately, if your project requirements involve authentication through WebSockets, which usually involves some sort of customized approach, then this library might not be a suitable solution. That said, if I understand @florianbepunkt's solution correctly, that they establish an unauthenticated connection first (to eliminate the possibility of a connectivity issue) before adding auth query parameters, then I believe that can be handled just as easily with this library:
const customUseWebSocket = (
connectionUrl: string,
authUrl: string,
options: Options,
connect: boolean,
): ReturnType<typeof useWebSocket> & { authError: Error } => {
const lastAuthError = useRef<Error>(null);
const [currentUrl, setCurrentUrl] = useState<string>(connectionUrl);
const {
readyState,
...useWebSocketReturnValue,
} = useWebSocket(currentUrl, {
...options,
onError: error => lastAuthError.current = error,
}, connect);
useEffect(() => {
if (readyState === ReadyState.OPEN && currentUrl === connectionUrl) {
lastAuthError.current = null;
setCurrentUrl(authUrl);
}
}, [readyState, currentUrl, authUrl]);
return {
...useWebSocketReturnValue,
readyState: connectionUrl === authUrl ? readyState : ReadyState.CONNECTING //Or ReadyState.CLOSED, depending on how you want this pre-authentication step treated
authError: connectionUrl === authUrl ? lastAuthError.current : null,
};
};
from react-use-websocket.
I believe, we didn't. We first checked connectivity before authenticating. Then we treated every error before a successful auth (that was not due to lack of connection) as an authentication error. It was not perfect but good enough for our use case.
Another approach we discussed was to use an http api for authentication... it depends on your use case whether this is a viable approach, but the idea was to use http api with an authorizer that would call a step function to create a short-lived hash (like an OTP) that would be sent to the user and the user would transmit the otp via websocket. But we discarded this approach as to complex, since the before mentioned solution was good enough. Hope this helps.
from react-use-websocket.
Thanks @florianbepunkt and @robtaussig for the suggestions (and @robtaussig for maintaining this cool library)! Yea having researched my issue, there's no problem with this package at all 😄 The WebSocket api itself seems designed not to expose the HTTP response code of the WebSocket handshake to javascript, so the default browser implementation is not advantageous in this respect. I'll think about how to solve this for my use case, drawing on your suggestions
from react-use-websocket.
hi @florianbepunkt, I have the same use case, did you manage to resolve it?
from react-use-websocket.
@qmg-rwaller No, we skipped using this lib in the end and used a custom websocket client, based on the default browser implementation.
from react-use-websocket.
Thanks, I may have to do the same. If you don't mind me asking, how did you access the Unauthorized HTTP status code / error message (from AWS WebSocket API Gateway) with your custom client? The default browser implementation doesn't seem to provide anything more than this module, and apparently the WebSocket spec forbids exposing the reason to scripts !
from react-use-websocket.
Related Issues (20)
- How to reconnect after reconnect attempt exceeded? HOT 2
- How do you disconnect when the react page refeshes? HOT 2
- Why's `setMessageHistory` updater function used as dependency in the example code? HOT 2
- One websocket connection with multiple queues to subscribe to HOT 2
- Back-Port the Generic Type Implementation for lastJsonMessage?
- a
- Error handling for async url callback function HOT 2
- CHANGELOG or Releases HOT 1
- After connecting to ws, there will be undefined messages in the ws cache message queue HOT 1
- lastJsonMessage incorrectly shown in README.md
- Question: How to use with redux-saga HOT 1
- Does the websocket disconnect on unmount? HOT 7
- How do I send Authorization headers (Bearer Token) with the message? HOT 2
- I don't see the heartbeat property in the options? HOT 1
- heartbeat seems not working as expected HOT 1
- Blocks UI thread HOT 9
- Heartbeat with ws.ping() HOT 1
- misclicked submit
- Ready state timeout not working as excpected
- The current state and the future of this library? HOT 8
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-use-websocket.