Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
The WebSocket API is one of the most common ways to communicate with servers over a stateful connection that allows you to both send and receive events async.
However, it is one of the most annoying things to do as a programmer because you have to coordinate between 4 separate callbacks:
open
,close
,message
, anderror
. How do you handle these callbacks properly given that they could be received in any order? You can either maintain an ad-hoc state machine and consult it within every callback, or you can use this contrib module which properly sequences the lifecycle of events into a single, coherent computation that is always resumed at the right point.Approach
Use the WebSocket:
Already at this point, you're a leg up because the actual
useWebSocket()
operation does not return until the socket has connected and successfully received theopen
event. Furthermore, it also has installed a handler for theerror
event that will crash the resource if a connection error is received at any point.Then, you can send data to the WebSocket just as you would normally.
And finally, you can receive data from the socket as a stream of
MessageEvents
that is closed with aCloseEvent
:There is no
close()
method on the web socket resource because it will be closed automatically whenever it passes out of scope.