0.0.2 • Published 6 years ago

simple-redux-websocket-middleware v0.0.2

Weekly downloads
6
License
MIT
Repository
-
Last release
6 years ago

Simple Redux WebSocket Middleware

Simple redux websocket middleware for browser or node

Installation

npm install --save simple-redux-websocket-middleware

Usage

For an example of how to use this middleware in node or the browser, see this project.

Add the middleware to your redux store

import createWebSocketMiddleware from 'simple-redux-websocket-middleware';
import { createStore, applyMiddleware } from 'redux';

let store = createStore(
  reducer,
  {},
  applyMiddleware(createWebSocketMiddleware())
);

Open websocket connections

store.dispatch({
  type: 'WEBSOCKET/REQUEST/OPEN',
  payload: {
    id: 'coinbase', // you pick an id per connection
    url: 'wss://ws-feed.exchange.coinbase.com'
  }
});

store.dispatch({
  type: 'WEBSOCKET/REQUEST/OPEN',
  payload: {
    id: 'gemini',
    url: 'wss://api.gemini.com/v1/marketdata/btcusd'
  }
});

Handle messages received by the websockets in your reducer:

function reduce(state, action) {
  if (action.type == 'WEBSOCKET/EVENT/MESSAGE') {
    if (action.payload.id == 'gemini') {
      return reduceGemini(state, action);
    } else if (action.payload.id == 'coinbase') {
      return reduceCoinbase(state, action);
    }
  } else {
    return state;
  }
}

License

MIT