Blog>
Snippets

Creating a Stream Handler with createAsyncThunk

Demonstrate how to create a streaming data handler using createAsyncThunk that listens to a data source and dispatches actions continuously.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Define a type for your streaming data if needed (optional)
// Example: type StreamData = { ... };

// Creating the stream handler thunk
export const streamDataHandler = createAsyncThunk(
  'data/stream',
  async (_, { dispatch, signal }) => {
    const listener = data => {
      // Handle the incoming streaming data
      // Example: dispatch(dataReceived(data));
    };

    const source = new EventSource('/streaming-endpoint');
    source.onmessage = event => listener(JSON.parse(event.data));

    // Listen for the abort event to close the stream if needed
    signal.addEventListener('abort', () => {
      source.close();
    });
  }
);
This code defines an asynchronous thunk for handling streaming data using an EventSource. It listens for new messages from a specified endpoint and dispatches actions accordingly. The signal parameter is used to listen to abort events to terminate the data stream when the thunk is cancelled.