klugjo / klugjo.github.io

🌐 My blog @
http://www.codeblocq.com/
3 stars 2 forks source link

How to receive messages from web sockets using redux-saga - CodeBlocQ #6

Open klugjo opened 6 years ago

klugjo commented 6 years ago

http://www.codeblocq.com/2017/08/How-to-receive-messages-from-web-sockets-using-redux-saga/

HekoBoii commented 6 years ago

Thank you so much, honestly, probably the best guide on redux-sagas w/ Websockets. 10/10

irmantasra commented 6 years ago

I had problems with eventChannel implementation, because for me mySocket.onmessage() was null. I have slightly modified your example:

import { takeEvery, eventChannel } from 'redux-saga';
import { put, call, take } from 'redux-saga/effects';
import { INITIALIZE_WEB_SOCKETS_CHANNEL,  WEBSOCKET_MESSAGE_RECEIVED } from '../actions';

function* createEventChannel(mySocket ) {
    return eventChannel(emit => {
        mySocket .onmessage = message => {
                 return emit ({ type: WEBSOCKET_MESSAGE_RECEIVED,  message });
            }
        };

        return () => {
            mySocket .close();
        };
    });
}

function* initializeWebSocketsChannel(action) {
    console.log('initialize websocket');
    const mySocket = new WebSocket("ws://www.xyz.com/socketServer", "protocol");
    const channel = yield call(createEventChannel, mySocket );

    while (true) {
        const action = yield take(channel);
        yield put(action);
    }
}

export default function* mySaga() {
    yield [
        takeEvery(INITIALIZE_WEB_SOCKETS_CHANNEL, initializeWebSocketsChannel)
    ];
}

For me this version works fine. Anyway, thanks for example structure :)