Redux reconnecting socket
Redux middleware and reducer for creating a websocket connection.
Features
- Send messages to the server simply by adding
sendToServer: true
to your actions. - Messages received from the server are automatically dispatched as actions.
- Automatically tries to reconnect when the connection drops.
- The
state.connection.connected
boolean is available in your store. - Optional: Use promises if you are expecting a response from the server after a certain message.
Installation
npm install --save redux-reconnecting-socket
Usage
1. Configure it in your middleware
;; const store = ;
2. Configure it in your root reducer (optional)
Only needed if you want to use the state.connection.connected
boolean.
;; const rootReducer = ; const defaultAppState = // ... other reducers connection: defaulReduxReconnectingSocketState;
socketConnect
action in your app component
3. Dispatch a ; Component { const dispatch = thisprops; ; } ...
sendToServer: true
to your action types
4. Send messages to the server by adding ;
5. Listen to server messages in your own middlewares and reducers
Whenever the server sends a message over the web socket, the message is automatically dispatched as an action.
promise: true
to your action types
6. Emulate request/responses by adding const request = ; request;
Whether the promise will be resolved or rejected depends on the error boolean in the message from the server:
type: 'MY_SERVER_RESPONSE' requestId: 1 // the same request id that was sent to the server error: true // true would cause the promise to be rejected
A numeric requestId
will automatically be generated and added in the message to
the server. When the server sends a message that includes the same requestId
,
the request promise will be completed.
Additionally, you have the option to cancel requests:
const request = ; request;
Three things will happen when you cancel
a request:
- The message from the server with this
requestId
will be ignored. It will not be dispatched. - The
request
promise will be rejected. - A
CANCEL_REQUEST
message will be sent to the server:
type: 'CANCEL_REQUEST' requestId: 1