reduxjs / redux

A JS library for predictable global state management
https://redux.js.org
MIT License
60.88k stars 15.27k forks source link

Redux and Sockets #1815

Closed Genbel closed 8 years ago

Genbel commented 8 years ago

Hi,

I'm new with that technology React-Redux and I would like your help with some implementation.

I want to implement one chat application with sockets (socket.io). First, the user has to sign up ( I use passport in the server side) and after, if the sign up is successful the user has to connect to the webSocket.

I thought that the best will be to use a middleware like a pipe for all the actions and depending of what kind of action gets the middleware, do different things.

Code Snippet:

----- socketMiddleware.js ----

import { AUTH_USER,  MESSAGE } from '../actions/types';

import * as actions from 'actions/socket-actions';

import io from 'socket.io-client';

const socket = null;

export default function ({ dispatch }) {

    return next => action => {

        if(action.type == AUTH_USER) {

            socket = io.connect(`${location.host}`);

            socket.on('message', data => {

               store.dispatch(actions.addResponse(action.data));

            });

        }

        else if(action.type == MESSAGE && socket) {

            socket.emit('user-message', action.data);

            return next(action)

        }

    }

}

------ index.js -------

import {createStore, applyMiddleware} from 'redux';

import socketMiddleware from './socketMiddleware';

const createStoreWithMiddleware = applyMiddleware(

  socketMiddleware

)(createStore);

const store = createStoreWithMiddleware(reducer);

<Provider store={store}>

    <App />

</Provider>

What do you think about that practise, is it a better implementation?

Kind Regards,

Kevin

markerikson commented 8 years ago

This is a usage question, and should really be asked over on Stack Overflow instead of the issues list.

That said, the basic description seems reasonable at first glance. You may also be interested in looking at some of the existing middleware packages for things like websockets and such - might be useful. I have a list of middlewares at https://github.com/markerikson/redux-ecosystem-links/blob/master/middleware.md.