Blog>
Snippets

Implementing Cancellation in API Polling

Demonstrate how to implement a cancellation feature for an ongoing API poll by dispatching a cancel action that is handled properly with createAsyncThunk.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
Import the necessary functions from Redux Toolkit and axios for making API calls.
// Async thunk action creator for polling
export const pollApiData = createAsyncThunk(
  'api/pollData',
  async ({ url, interval }, { dispatch, getState } ) => {
    const poll = setInterval(async () => {
      try {
        const response = await axios.get(url);
        dispatch(apiPollSuccess(response.data));
      } catch (error) {
        dispatch(apiPollFailure(error.toString()));
      }
    }, interval);

    // Attach the interval id to the async thunk object to later clear it for cancellation
    return poll;
  }
);
Create an async thunk for polling an API. An interval ID is returned for possible cancellation.
// Slice to handle the polling states
const apiSlice = createSlice({
  name: 'api',
  initialState: {
    data: null,
    error: null,
    polling: null
  },
  reducers: {
    apiPollSuccess: (state, action) => {
      state.data = action.payload;
    },
    apiPollFailure: (state, action) => {
      state.error = action.payload;
    },
    stopPolling: (state) => {
      if (state.polling) clearInterval(state.polling);
      state.polling = null;
    }
  },
  extraReducers: (builder) => {
    builder.addCase(pollApiData.fulfilled, (state, action) => {
      state.polling = action.payload;
    });
  }
});

// Export actions for use in components
dstexport const { apiPollSuccess, apiPollFailure, stopPolling } = apiSlice.actions;
Create a slice with reducers for success, failure, and stopping the polling. The interval ID is stored in the state for cancellation.
// Usage of the stopPolling action in a component
dispatch(stopPolling());
Example of how to dispatch the stopPolling action from a component.