redux-saga-async-action
Dispatching an action handled by redux-saga returns promise. It looks like redux-thunk, but with pure action creators.
store
redux-saga-async-action
uses Flux Standard Action to determine action'spayload
,failure
etc.
Install
$ npm install --save redux-saga-async-action
Basic setup
Add middleware
to your redux configuration (before redux-saga middleware):
const sagaMiddleware = const store =
Usage
Add meta.async
to your actions and receive key
on response actions:
const resourceCreateRequest = type: 'RESOURCE_CREATE_REQUEST' // you can name it as you want payload: data // promise will return payload meta: async: true ^ const resourceCreateSuccess = ^ type: 'RESOURCE_CREATE_SUCCESS' // name really doesn't matter payload: detail meta: async: key ^ const resourceCreateFailure = ^ type: 'RESOURCE_CREATE_FAILURE' error: true // redux-saga-async-action will use this to determine if that's a failed action payload: error meta: async: key ^
redux-saga-async-action
will automatically transform your request action and inject a key
into it.
Handle actions with redux-saga
like you normally do, but you'll need to grab key
from the request action and pass it to the response actions:
// worker saga// async will be transformed in something like 'RESOURCE_CREATE_REQUEST_1234567890123456_REQUEST'// the 16 digits in the middle are necessary to handle multiple async actions with same type { ^ try const detail = ^ catch e ^ } // watcher saga { while true const payload meta = ^ ^ }
Dispatch the action from somewhere. Since that's being intercepted by asyncMiddleware
cause you set meta.async
on the action, dispatch will return a promise.
store
Usage with selectors
To use isPending
and hasFailed
selectors, you'll need to add the asyncReducer
to your store:
const reducer =
Now you can use selectors on your containers:
const mapStateToProps = loading: error:
API
isPending
Tells if an action is pending
Parameters
Examples
const mapStateToProps = fooIsPending: fooOrBarIsPending: anythingIsPending:
Returns boolean
hasFailed
Tells if an action has failed
Parameters
Examples
const mapStateToProps = fooHasFailed: fooOrBarHasFailed: anythingHasFailed:
Returns boolean
License
MIT © Diego Haz