🚀 Big News:Socket Has Acquired Secure Annex.Learn More →
Socket
Book a DemoSign in
Socket

redux-ws

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

redux-ws

Redux middleware for WebSockets communication.

latest
Source
npmnpm
Version
0.2.0
Version published
Maintainers
1
Created
Source

Redux WebSockets

npm version

WebSockets middleware for Redux. If you ever used Redux Thunk you already know how to use this.

What Does it Do?

Redux WebSockets exposes a socket connection to any action creator that returns a function instead of a plain object. This way you can easily 'reach' your long-living socket from any thunk that goes through Redux.

Usage

Write action creators that return functions instead of objects. Those functions will be immediately called with an object containing the socket, dispatch, and getState as the argument.

Note that this is a bit different from Redux Thunk — you get passed on object, not dispatch/getState/socket directly. This is done to make it easier to reach either of them, without having to 'walk over' the parameters every time. I highly recommend using destructuring to get to the right parts of the object. See below.

// An action creator returns a function that gets passed an object containing
// the socket, dispatch, and getState as an argument. I am using ES2015
// destructuring to take socket and dispatch from this object and
// subsequently use it.
function subscribeToUpdates() {
  return ({ socket, dispatch }) => {
    socket.on('update', dispatch(reactToUpdate()));
  };
}

// Regular Redux action creator...
function reactToUpdate() {...}

Installation

Install from npm.

npm install --save redux-ws

Instantiate, pass the middleware creator your socket, and add to your middleware stack.

import { createStore, applyMiddleware } from 'redux';
import createSocketMiddleware from 'redux-ws';
import io from 'socket.io-client';
import reducer from './reducers/index';

const socketMiddleware = createSocketMiddleware(io('http://example.com/socket'));

const store = createStore(
  reducer,
  applyMiddleware(socketMiddleware)
);

// Now just write your actions...

The above example uses socket.io, but I don't see any reason this middleware couldn't be used with other WebSockets libraries — all it does is exposes your socket process to thunks. Check out the source.

Keywords

redux

FAQs

Package last updated on 24 Apr 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts