Data Stream Cancellation with createAsyncThunk
Use createAsyncThunk to start a data stream and showcase how to properly cancel the stream to avoid memory leaks and other potential issues.
import { createAsyncThunk } from '@reduxjs/toolkit';
// Assume this function starts a data stream and returns a promise
const startDataStream = (signal) => {
// API call or other streaming logic goes here
// The signal parameter is used to listen for cancellation
return new Promise((resolve, reject) => {
const intervalId = setInterval(() => {
console.log('Data stream tick');
// Fake data replace the line below with actual data
const data = 'data';
resolve(data);
}, 1000);
// Listen for cancellation
signal.addEventListener('abort', () => {
clearInterval(intervalId);
reject(new Error('DataStream cancelled by the user'));
});
});
};
// createAsyncThunk action creator for starting the data stream
export const fetchDataStream = createAsyncThunk(
'dataStream/fetch',
async (_, { signal }) => {
const data = await startDataStream(signal);
return data;
}
);
This code defines a function 'startDataStream' which mocks starting a data stream. It is intended to be replaced with actual data streaming logic. The function returns a promise that resolves with data every second, until it is canceled. The 'fetchDataStream' action creator uses createAsyncThunk to handle the lifecycle of the stream, including cancellation. The 'signal' object provided by `createAsyncThunk` is used to cancel the interval when the action is dispatched with a corresponding cancellation.