Chaining Actions
When a promise is resolved, one might want to dispatch additional actions in response. One example could be changing the route after a user is successfully signed in. Another could be showing an error message after a request fails.
First, note this behavior uses thunks. You will need to include Redux Thunk in your middleware stack.
Note: Redux Thunk is a middleware that enables action creators to return a function instead of an object (hence the name "thunk"). The returned function is called with a dispatch argument, which is what you can use to chain actions.
1
const foo = () => {
2
return dispatch => {
3
​
4
return dispatch({
5
type: 'TYPE',
6
payload: new Promise()
7
}).then(() => dispatch(bar()));
8
};
9
}
Copied!
If you need to chain several actions, using Promise.all is suggested.
1
const foo = () => {
2
return dispatch => {
3
​
4
return dispatch({
5
type: 'TYPE',
6
payload: Promise.all([
7
dispatch(bar()),
8
dispatch(baz())
9
])
10
});
11
};
12
}
Copied!
When handling a promise with then, the parameter is an object with two properties: (1) the "value" (if the promise is fulfilled) or the "reason" (if the promise is rejected) and (2) the object of the dispatched action.
1
// fulfilled promise
2
const foo = () => {
3
return dispatch => {
4
​
5
return dispatch({
6
type: 'FOO',
7
payload: new Promise(resolve => {
8
resolve('foo'); // resolve the promise with the value 'foo'
9
})
10
}).then(({ value, action }) => {
11
console.log(value); // => 'foo'
12
console.log(action.type); // => 'FOO_FULFILLED'
13
});
14
};
15
}
16
​
17
// rejected promise
18
const bar = () => {
19
return dispatch => {
20
​
21
return dispatch({
22
type: 'BAR',
23
payload: new Promise(() => {
24
throw new Error('foo'); // reject the promise for the reason 'bar'
25
})
26
}).then(() => null, error => {
27
console.log(error instanceof Error) // => true
28
console.log(error.message); // => 'foo'
29
});
30
};
31
}
Copied!
Rejected promises can also be handled with .catch().
1
// rejected promise with throw
2
const baz = () => {
3
return dispatch => {
4
​
5
return dispatch({
6
type: 'BAZ',
7
payload: new Promise(() => {
8
throw new Error(); // throw an error
9
})
10
}).catch((error) => {
11
console.log(error instanceof Error) // => true
12
});
13
};
14
}
Copied!
Last modified 1yr ago
Copy link