Tools for coding with redux-thunk
npm i handy-thunks
The package provides easy way to create, enhance and compose thunks
in order to build flow of any complexity by using following tools:
- connected(selector)(thunk)
- loading(startAction, endAction)(...loadingArgs)(thunk)
- fallback(fallbackThunk)(thunk)
- followedBy(nextThunk)(thunk)
- cleanUp(cleaningThunk)(thunk)
- onlyIf(predicate)(thunk)
- chained(keySelector)(thunk)
- single(keySelector)(thunk)
- postponed(delay, keySelector)(thunk)
- lazy(thunk)
./src/flows.js (complicated thunks):
import { queue, all, connected, loading } from 'handy-thunks';
import { getUser } from './store/users';
import { loadUser, loadContracts, loadOffers } from './thunks';
const withUserId = connected(state => getUser(state).id);
const withLoading = loading(startLoading, endLoading)('ALL');
const fetchUserData = queue(
loadUser,
all(
withUserId(loadContracts),
withUserId(loadOffers),
),
);
export default withLoading(fetchUserData);
./src/thunks.js (simple thunks):
import { compose } from 'redux';
import api from './api';
import { saveUser, readUser } from './store/users';
import { saveUserContracts, readContracts } from './store/contracts';
import { saveUserOffers, readOffers } from './store/offers';
export const loadUser = () => dispatch => api()
.get('/user')
.then(compose(dispatch, saveUser, readUser));
export const loadContracts = userId => dispatch => api()
.get(`/users/${userId}/contracts`)
.then(compose(dispatch, saveUserContracts, readContracts));
export const loadOffers = userId => dispatch => api()
.get(`/users/${userId}/offers`)
.then(compose(dispatch, saveUserOffers, readOffers));