Blog>
Snippets

Reducer Logic for Handling API Polling States

Provide a code example on how to write a reducer that listens to the fulfilled, pending, and rejected states of a polling thunk, and handles the state updates correctly.
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  data: null,
  isLoading: false,
  error: null
};

const pollSlice = createSlice({
  name: 'poll',
  initialState,
  reducers: {},
  extraReducers: {
    // Handle pending state
    pollStarted: (state, action) => {
      state.isLoading = true;
      state.error = null;
    },
    // Handle successfully fetched data
    pollFulfilled: (state, action) => {
      state.isLoading = false;
      state.data = action.payload;
    },
    // Handle errors
    pollRejected: (state, action) => {
      state.isLoading = false;
      state.error = action.error;
    }
  }
});

export default pollSlice.reducer;
This reducer is created using Redux Toolkit's createSlice utility. It defines an initial state with 'data', 'isLoading', and 'error' fields. The extraReducers property handles actions for pending (pollStarted), fulfilled (pollFulfilled), and rejected (pollRejected) states of a thunk-based asynchronous polling operation.