0

What should be my approach towards implementing websocket using boilerplate and saga, I would like to connect the websocket during starting of the application and reconnect when connection drops.

I am think of using fork for sending and receiving but still should I use actionChannel?

I need to cancel the forked send and receive threads when connection drops and respawn when connection comes back.

Some general questions: (not related to react/redux-saga)

What should be my approach when my applications wants to send messages during disconnected state? Should I Also I have request-response where I send a request number in data and server responds me back, How should I handle this?

Maru
  • 41
  • 2
  • 7
  • Welcome to Stackoverflow! You will get great answers here, but please provide some more information what you tried so far. Most importantly, link some code in here (preferably to a fiddle/bin/pen). – Alp Apr 04 '17 at 15:23

1 Answers1

0

In practice there are several strategy which can be used for switching on of socket.io in redux infrastructure:

First, there are ready decisions in the form of middleware, for example https://www.npmjs.com/package/redux-socket.io

Secondly, it is possible to act simpler more cunning. At the moment when redux store and saga is created, it is at the same time possible to create also necessary client instance of socket.io, and further already logic of the functional closure.

Following example fully cover your case. Just setup MESSAGES_MAP map with name of events which should be mapped to Redux actions.

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import socketIO from 'socket.io-client';
import YourRootContainter from './YourRootContainter';

const MESSAGES_MAP = {
    'MESSAGE_1': 'REDUX_ACTION_1',
    'MESSAGE_2': 'REDUX_ACTION_2'
};

Promise.resolve(createSagaMiddleware()).then(saga => ({
    store: (compose(applyMiddleware(saga))(createStore))(
        YOUR_REDUCER,
        YOUR_INITIAL_STATE
    ),
    socketClient: socketIO(YOUR_SOCKET_URL, {
        path: YOUR_EXCHANGE_URL_PATH
    }),
    saga
})).then(({ saga, store, socketClient }) => (
    Object.keys(MESSAGES_MAP).forEach(name => (
        socketClient.on(name, event => store.dispatch({
            type: MESSAGES_MAP[name],
            payload: { ...event }
        }))
    )), 
    saga.run(YOUR_SAGA_ENTRY_POINT),
    store
)).then(store => render(
    (<Provider store={store}>
        <YourRootContainter />
    </Provider>), 
    document.getElementById('root')
));
Vladislav Ihost
  • 2,127
  • 11
  • 26