Permalink
4f3460f Jul 7, 2018
3 contributors

Users who have contributed to this file

@pburtchaell @piu130 @franklixuefei
94 lines (69 sloc) 1.5 KB

Introduction

Installation

First, install the middleware with npm:

npm i redux-promise-middleware -s

Or with Yarn:

yarn add redux-promise-middleware

Setup

Import the middleware and include it in applyMiddleware when creating the Redux store:

import promiseMiddleware from 'redux-promise-middleware'

composeStoreWithMiddleware = applyMiddleware(
  promiseMiddleware(),
)(createStore)

Use

Dispatch a promise as the value of the payload property of the action.

const foo = () => ({
  type: 'FOO',
  payload: new Promise(),
})

A pending action is immediately dispatched.

{
  type: 'FOO_PENDING'
}

Once the promise is settled, a second action will be dispatched. If the promise is resolved a fulfilled action is dispatched.

{
  type: 'FOO_FULFILLED'
  payload: {
    ...
  }
}

On the other hand, if the promise is rejected, a rejected action is dispatched.

{
  type: 'FOO_REJECTED'
  error: true,
  payload: {
    ...
  }
}

If you need to send extra information not included in the payload property, you can use the meta property.

const foo = () => ({
  type: 'FOO',
  payload: new Promise(),
  meta: {
    ...
  },
})

That's it!

TypeScript

The middleware does support TypeScript.

Further Reading