Blog>
Snippets

Handling WebSocket Communication

Explain how to handle WebSocket connections and messages in a Redux-Saga task using effects like `take`, `call`, and `put` for real-time data handling.
import { take, call, put } from 'redux-saga/effects';
function createWebSocketChannel() {
  // This function creates an event channel from a given socket
  // Connect your WebSocket here and return the channel
}
Define a utility function to create a WebSocket channel.
import { eventChannel } from 'redux-saga';
function createWebSocketChannel(socket) {
  return eventChannel(emit => {
    socket.onmessage = event => {
      // When a message is received, emit an action
      emit({ type: 'WEBSOCKET_MESSAGE_RECEIVED', payload: JSON.parse(event.data) });
    };

    // Return the unsubscribe method
    return () => {
      socket.close();
    };
  });
}
Implements the createWebSocketChannel function using 'eventChannel' to handle incoming WebSocket messages.
import { call, put, take } from 'redux-saga/effects';
function* handleWebSocketConnection(socketUrl) {
  const socket = new WebSocket(socketUrl);
  const channel = yield call(createWebSocketChannel, socket);

  while (true) {
    const action = yield take(channel);
    // Dispatch action received from WebSocket to the store
    yield put(action);
  }
}
WebSocket connection saga that listens to messages from the WebSocket channel and dispatches them to the Redux store.