Blog>
Snippets

Creating an eventChannel for WebSocket Events

Show how to create an eventChannel that listens to WebSocket messages and dispatches actions to the Redux store accordingly.
import { eventChannel } from 'redux-saga';
Import eventChannel from redux-saga.
import { take, put, call } from 'redux-saga/effects';
Import necessary effects from redux-saga.
function createSocketChannel(socket) { 
    return eventChannel(emit => { 
        socket.on('message', (data) => { 
            emit(data);
        }); 
        
        return () => { 
            socket.off('message', emit);
        };
    });
}
Creates an eventChannel that listens to WebSocket messages. When a message is received, it emits the data to be used by a saga.
function* listenToSocket(socket) { 
    const socketChannel = yield call(createSocketChannel, socket); 
    while (true) { 
        const payload = yield take(socketChannel); 
        yield put({type: 'SOCKET_MESSAGE_RECEIVED', payload});
    }
}
A generator function that listens to the created socketChannel. Whenever a message is emitted through the channel, it dispatches an action to the store.