Introduction

Installation

First, install the middleware.
1
npm i redux-promise-middleware -s
Copied!

Setup

Import the middleware and include it in applyMiddleware when creating the Redux store:
1
import promise from 'redux-promise-middleware'
2
​
3
composeStoreWithMiddleware = applyMiddleware(
4
promise,
5
)(createStore)
Copied!

Use

Dispatch a promise as the value of the payload property of the action.
1
const foo = () => ({
2
type: 'FOO',
3
payload: new Promise()
4
});
Copied!
A pending action is immediately dispatched.
1
{
2
type: 'FOO_PENDING'
3
}
Copied!
Once the promise is settled, a second action will be dispatched. If the promise is resolved a fulfilled action is dispatched.
1
{
2
type: 'FOO_FULFILLED'
3
payload: {
4
...
5
}
6
}
Copied!
On the other hand, if the promise is rejected, a rejected action is dispatched.
1
{
2
type: 'FOO_REJECTED'
3
error: true,
4
payload: {
5
...
6
}
7
}
Copied!
That's it!

Further Reading

Last modified 3yr ago