💫
Promise Middleware
  • Introduction
  • Getting Started
    • Introduction
    • Design Principles
  • Guides
    • Catching Errors Thrown by Rejected Promises
    • Chaining Actions
    • Comparison to other promise middleware
    • Custom Type Delimiters
    • Custom Types
    • Optimistic Updates
    • Use with Async/Await
    • Use with Reducers
    • Use with Redux Actions
    • Use with Redux Promise Actions
    • Use with Promises Resolved with Null Values
  • Upgrade Guides
    • Upgrade from 5.x to 6.0.0
    • Upgrade from 4.x to 5.0.0
    • Upgrade from 3.x to 4.0.0
    • Release History
Powered by GitBook
On this page
  • Action Types
  • Large Applications
  1. Guides

Use with Reducers

Handling actions dispatched by Redux promise middleware is simple by default.

const FOO_TYPE = 'FOO';

// Dispatch the action
const fooActionCreator = () => ({
  type: FOO_TYPE
  payload: Promise.resolve('foo')
});

// Handle the action
const fooReducer = (state = {}, action) => {
  switch(action.type) {
    case `${FOO_TYPE}_PENDING`:
      return;

    case `${FOO_TYPE}_FULFILLED`:
      return {
        isFulfilled: true,
        data: action.payload
      };

    case `${FOO_TYPE}_REJECTED`:
      return {
        isRejected: true,
        error: action.payload
      };

    default: return state;
  }
}

Action Types

Optionally, the default promise suffixes can be imported from this module.

import { ActionType } from 'redux-promise-middleware';

This can be useful in your reducers to ensure types are more robust.

const FOO_PENDING = `FOO_${ActionType.Pending}`;
const FOO_FULFILLED = `FOO_${ActionType.Fulfilled}`;
const FOO_REJECTED = `FOO_${ActionType.Rejected}`;

Large Applications

In a large application with many async actions, having many reducers with this same structure can grow redundant.

import typeToReducer from 'type-to-reducer';

const BAR_TYPE = 'BAR';

// Dispatch the action
const barActionCreator = () => ({
  type: BAR_TYPE
  payload: Promise.resolve('bar')
});

// Handle the action
const barReducer = typeToReducer({
    PENDING: () => ({
      // ...
    }),
    REJECTED: (state, action) => ({
      isRejected: true,
      error: action.payload
    }),
    FULFILLED: (state, action) => ({
      isFulfilled: true,
      data: action.payload
    })
  }
}, {});
PreviousUse with Async/AwaitNextUse with Redux Actions

Last updated 6 years ago

To keep your reducers , you might see value in using a solution like .

DRY
type-to-reducer