Creating an Event Channel to Listen to Web Sockets
This example demonstrates how to create an event channel in Redux-Saga that listens to messages from a WebSocket connection, parses the incoming data, and dispatches actions to the Redux store based on the data received.
import { eventChannel } from 'redux-saga';
import { take, call, put } from 'redux-saga/effects';
import { websocketConnected, websocketMessageReceived } from './actions';
Import necessary effects from Redux-Saga and actions from the action creator.
function createWebSocketChannel(socket) {
return eventChannel(emit => {
socket.onmessage = event => {
const parsedData = JSON.parse(event.data);
emit(parsedData);
};
socket.onclose = () => {
emit(END);
};
return () => {
socket.close();
};
});
}
Defines a function that creates an event channel from a WebSocket object. It listens for messages and closes the channel when the socket closes.
function* listenForSocketMessages(socket) {
const socketChannel = yield call(createWebSocketChannel, socket);
try {
while (true) {
const payload = yield take(socketChannel);
yield put(websocketMessageReceived(payload));
}
} finally {
if (yield cancelled()) {
socketChannel.close();
}
}
}
Saga that listens for messages on the WebSocket channel and dispatches an action with the message payload to the Redux store. It also handles saga cancellation.
function* websocketSaga() {
const socket = new WebSocket('ws://example.com/socket');
socket.onopen = function() {
yield put(websocketConnected());
};
yield fork(listenForSocketMessages, socket);
}
Main saga that initiates the WebSocket connection and starts the listener saga.