Blog>
Snippets

Handling WebSocket Connections

Demonstrate the setup of a WebSocket connection using Redux-Saga, including listening for incoming messages and sending messages, utilizing the 'eventChannel' to manage the WebSocket events.
import { eventChannel } from 'redux-saga';
import { call, put, take, fork } from 'redux-saga/effects';
Import necessary functions from redux-saga. 'eventChannel' is used to wrap the WebSocket events.
function createWebSocketConnection() {
  return new WebSocket('ws://example.com/ws');
}
Function to create a new WebSocket connection.
function createSocketChannel(socket) {
  return eventChannel(emit => {
    socket.onmessage = (event) => {
      emit(event.data);
    };

    socket.onclose = () => {
      emit(new Error('WebSocket disconnected'));
    };

    // The subscriber must return an unsubscribe function
    return () => {
      socket.onmessage = null;
      socket.onclose = null;
    };
  });
}
Function to create an eventChannel from a WebSocket connection to handle incoming messages and disconnection.
function* watchOnMessage() {
  const socket = yield call(createWebSocketConnection);
  const socketChannel = yield call(createSocketChannel, socket);

  while (true) {
    try {
      const payload = yield take(socketChannel);
      yield put({type: 'WEBSOCKET_MESSAGE', payload});
    } catch(err) {
      console.error('socket error:', err);
      // implement error handling or reconnection logic here
    }
  }
}
Saga to watch for incoming messages over the WebSocket connection. Messages are dispatched as actions.
function* sendMessage(socket, message) {
  yield call([socket, socket.send], JSON.stringify(message));
}
Saga to send a message through the WebSocket connection.
function* startWebSocketSaga() {
  const socket = yield call(createWebSocketConnection);
  // Forking a task to handle incoming WebSocket messages
  yield fork(watchOnMessage);
  // Example of sending a message
  yield fork(sendMessage, socket, { type: 'GREET', payload: 'Hello WebSocket' });
}
Top-level saga to start the WebSocket connection and initiate listening for messages and sending a test message.