Blog>
Snippets

Managing Thunk States and Timeout Errors in Redux Reducer

Illustrate how to handle async thunk states and timeout errors within a Redux reducer to update the state accordingly.
// Define action types
const FETCH_DATA = 'FETCH_DATA';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_ERROR = 'FETCH_DATA_ERROR';
const FETCH_DATA_TIMEOUT = 'FETCH_DATA_TIMEOUT';

// Initial state for the reducer
const initialState = {
  data: null,
  loading: false,
  error: null,
  timeout: false
};

// Example reducer handling async thunk states and timeout errors
function dataReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_DATA:
      return { ...state, loading: true, error: null, timeout: false };
    case FETCH_DATA_SUCCESS:
      return { ...state, data: action.payload, loading: false };
    case FETCH_DATA_ERROR:
      return { ...state, loading: false, error: action.error, timeout: false };
    case FETCH_DATA_TIMEOUT:
      return { ...state, loading: false, timeout: true, error: 'Timeout error' };
    default:
      return state;
  }
}
This code defines a reducer that manages the application state related to an asynchronous data fetch operation. It handles actions representing various stages of the async request (start, success, error, and timeout) to update the state with the data, error messages, loading status, and timeout status.