Use with Redux Promise Actions
To use this middleware with redux-promise-middleware-actions, invoke createAsyncAction and return a promise from the payload creator.
1
import { createAsyncAction } from 'redux-promise-middleware-actions';
2
3
// Create an async action
4
const fooAction = createAsyncAction('FOO', async (url) => {
5
const response = await fetch(url);
6
return response.json();
7
});
8
9
// Use async action
10
dispatch(fooAction('https://some.url'));
Copied!
This would dispatch FOO_PENDING and FOO_FULFILLED with the data as the payload. fooAction has a reference to these action creators on the object itself, e.g. fooAction.pending(). You can listen for these in the reducer like this:
1
const reducer = (state, action) => {
2
switch (action.type) {
3
case String(fooAction.pending):
4
return {
5
...state,
6
pending: true,
7
};
8
case String(fooAction.fulfilled):
9
return {
10
...state,
11
data: action.payload,
12
error: undefined,
13
pending: false,
14
};
15
case String(fooAction.rejected):
16
return {
17
...state,
18
error: action.payload,
19
pending: false,
20
};
21
default:
22
return state;
23
}
24
};
Copied!
Last modified 3yr ago
Copy link