1.0.3 • Published 8 years ago

redux-simple-websocket v1.0.3

Weekly downloads
4
License
ISC
Repository
github
Last release
8 years ago

Simple websocket middleware for ReactJS

installation

npm i redux-simple-websocket

usage

create middleware and apply to redux store

import { createStore, applyMiddleware } from "redux"
import { createSimpleWebSocketMiddleware } from "redux-simple-websocket"

const store = createStore( reducer, {}, applyMiddleware( createSimpleWebSocketMiddleware() ) )

actions

import { connectWebSocketAction, closeWebSocketAction, sendDataToWebSocketAction } from "redux-simple-websocket"

// connect to a websocket
dispatch( connectWebSocketAction( endpoint ) )

// close websocket
dispatch( closeWebSocketAction( endpoint ) )

// send message to websocket
dispatch( sendDataToWebSocketAction( endpoint, message ) )

if websocket weren't connected, and you're trying to send data, the payload will be pushed to queue and wait for connection

events

all actions can be used by import

import { ActionTypes } from "redux-simple-websocket"

then you can listen action in your reducers

let defaultState = {
    // 0 == disconnect, 1 == connected
    connected: false,
    endpoint: "ws://localhost:8888/websocket",
    lastError: null,
    log: []
}

const connection = ( state = defaultState, action ) => {
    switch ( action.type ) {
        case ActionTypes.WEBSOCKET_CONNECTED:
            return {
                ...state,
                connected: true,
                log: state.log.concat( ["[OPEN] > " + action.endpoint] )
            }
        case ActionTypes.WEBSOCKET_ERROR:
            return {
                ...state,
                lastError: action.error,
                log: state.log.concat( ["[ERROR] > " + action.endpoint + "\n err" + action.error] )
            }
        case ActionTypes.WEBSOCKET_DISCONNECTED:
            return {
                ...state,
                connected: false,
                log: state.log.concat( ["[CLOSED] > " + action.endpoint] )
            }
        case ActionTypes.SEND_DATA_TO_WEBSOCKET:
            return {
                ...state,
                log: state.log.concat( ["[SEND] (" + action.endpoint + ") > " + JSON.stringify( action.payload )] )
            }
        case ActionTypes.RECEIVED_WEBSOCKET_DATA:
            return {
                ...state,
                log: state.log.concat( ["[RECV] (" + action.endpoint + ") < " + JSON.stringify( action.payload )] )
            }
    }
    return state
}
1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago

3.0.11

8 years ago

0.0.8

10 years ago

0.0.7

10 years ago

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago