Redux Axios Middleware

4.0.1 · maintenance · verified Wed Apr 22

Redux Axios Middleware is a Redux middleware designed to streamline data fetching using the popular Axios HTTP client within Redux applications. The current stable version is 4.0.1, with the last major release (v4.0.0) in March 2017, indicating a very slow release cadence, suggesting it's feature-complete or in maintenance mode rather than active development. Its key differentiators include directly integrating Axios request configurations into Redux actions, managing the full lifecycle of HTTP requests (start, success, error) with configurable action types and suffixes, and enabling promise chaining on dispatched actions for sequential logic or advanced error handling. It also supports defining and using multiple Axios clients for different APIs within a single Redux store.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `redux-axios-middleware` with a Redux store, configuring an Axios client, dispatching an action with a `payload.request` definition, and handling the resulting promise for success or failure.

import { createStore, applyMiddleware, combineReducers } from 'redux';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';

// Create a basic Axios client instance
const client = axios.create({
  baseURL: 'https://api.example.com',
  responseType: 'json',
  timeout: 5000
});

// Define a placeholder reducer (required by createStore)
const mockReducer = (state = {}, action) => {
  console.log('Dispatched action:', action.type, action.payload || action.error);
  return state;
};

// Combine reducers (even if just one for demonstration)
const reducers = combineReducers({
  data: mockReducer
});

// Create the Redux store with the middleware
const store = createStore(
  reducers,
  applyMiddleware(axiosMiddleware(client))
);

// Action creator for loading categories
export function loadCategories() {
  return {
    type: 'LOAD_CATEGORIES',
    payload: {
      request: {
        url: '/categories',
        method: 'GET'
      }
    }
  };
}

// Dispatch the action and handle the promise
store.dispatch(loadCategories())
  .then(response => {
    console.log('Categories loaded successfully:', response.payload.data);
  })
  .catch(error => {
    console.error('Failed to load categories:', error.error);
  });

// Example using `types` array for explicit action states
export function submitForm(formData) {
  return {
    types: ['SUBMIT_FORM_REQUEST', 'SUBMIT_FORM_SUCCESS', 'SUBMIT_FORM_FAILURE'],
    payload: {
      request: {
        url: '/form-data',
        method: 'POST',
        data: formData
      }
    }
  };
}

// Dispatch with custom types and chaining
const myFormData = { name: 'Test', value: 123 };
store.dispatch(submitForm(myFormData))
  .then(() => console.log('Form submitted successfully!'))
  .catch(error => console.error('Form submission failed:', error.error));

view raw JSON →