Use with Reducers
Handling actions dispatched by Redux promise middleware is simple by default.
1
const FOO_TYPE = 'FOO';
2
​
3
// Dispatch the action
4
const fooActionCreator = () => ({
5
type: FOO_TYPE
6
payload: Promise.resolve('foo')
7
});
8
​
9
// Handle the action
10
const fooReducer = (state = {}, action) => {
11
switch(action.type) {
12
case `${FOO_TYPE}_PENDING`:
13
return;
14
​
15
case `${FOO_TYPE}_FULFILLED`:
16
return {
17
isFulfilled: true,
18
data: action.payload
19
};
20
​
21
case `${FOO_TYPE}_REJECTED`:
22
return {
23
isRejected: true,
24
error: action.payload
25
};
26
​
27
default: return state;
28
}
29
}
Copied!

Action Types

Optionally, the default promise suffixes can be imported from this module.
1
import { ActionType } from 'redux-promise-middleware';
Copied!
This can be useful in your reducers to ensure types are more robust.
1
const FOO_PENDING = `FOO_${ActionType.Pending}`;
2
const FOO_FULFILLED = `FOO_${ActionType.Fulfilled}`;
3
const FOO_REJECTED = `FOO_${ActionType.Rejected}`;
Copied!

Large Applications

In a large application with many async actions, having many reducers with this same structure can grow redundant.
To keep your reducers DRY, you might see value in using a solution like type-to-reducer.
1
import typeToReducer from 'type-to-reducer';
2
​
3
const BAR_TYPE = 'BAR';
4
​
5
// Dispatch the action
6
const barActionCreator = () => ({
7
type: BAR_TYPE
8
payload: Promise.resolve('bar')
9
});
10
​
11
// Handle the action
12
const barReducer = typeToReducer({
13
PENDING: () => ({
14
// ...
15
}),
16
REJECTED: (state, action) => ({
17
isRejected: true,
18
error: action.payload
19
}),
20
FULFILLED: (state, action) => ({
21
isFulfilled: true,
22
data: action.payload
23
})
24
}
25
}, {});
Copied!
Last modified 2yr ago