Redux Awaiter
Redux Awaiter is a Redux middleware for giving opportunities to await and receive actions in anywhere.
It's tiny (gzip < 1kB, no dependencies).
Motivation
Redux Awaiter is designed to help us manage local state conveniently.
It's inspired by Redux Saga, but the problems they solve are totally different.
Example
We can use Redux Awaiter and async/await
to pause execution until an expected action has been dispatched.
PureComponent state = loading: false ; async { const actions: fetchUserList = thisprops; ; this; // start loading, until RECEIVE_USER_LIST has been dispatched await ; // reducers may update `users` in redux store, stop loading this; } { const users = thisprops; // `users` is mapped from redux store const loading = thisstate; return <Spin loading=loading> <ul> users </ul> </Spin> ; }
Installation
npm i redux-awaiter
Documentation
Type Definition
Redux Awaiter is written in TypeScript.
The internal type definition is based on flux standard action.
;
A pattern determines whether an action is matching.
;
object
pattern is not supported, use a function instead.
API
createAwaiterMiddleware
;; const awaiterMiddleware = ; const store = ;
take
;
take
receives a pattern as its single argument, and returns a Promise which contains the first matching action.
const action = await ; // action.type should be RECEIVE_DATA
takeAllOf
;
takeAllOf
receives an array of patterns as its single argument, and returns a Promise which contains an array of actions corresponding to patterns.
Internally, takeAllOf(patterns)
is the same with Promise.all(patterns.map(take))
.
If you need to await and receive multiple actions in specific order, use multiple await take()
instead.
const payload: articles payload: users = await ;
takeOneOf
;
takeOneOf
receives an array of patterns as its single argument, and returns a Promise which contains the first action matching with one of patterns.
Internally, takeOneOf(patterns)
is the same with Promise.race(patterns.map(take))
.
const type = await ;if type === 'FETCH_USER_SUCCESS' // success else // failure
You might not need takeOneOf
.
const type = await ;
DO NOT OVERUSE
Avoid relying on props MUTATION!
This may cause unexpected behaviors, or make your components difficult to maintain.
async { const data = thisprops // this.props.data is mapped from redux store. // dispatch an action and do some async call (e.g. xhr, fetch) await ; // receive new data and update redux store by reducer // DANGER: this.props.data is MUTATED! console; // Assertion failed!}