fsa-redux-thunk
v2.3.0
Published
FSA Thunk middleware for Redux.
Maintainers
Readme
FSA Redux Thunk
Fork of redux-thunk middleware that enforces
Flux Standard Actions.
Installation
npm install --save redux-thunkor
yarn add fsa-redux-thunkThen, to enable Redux Thunk, use applyMiddleware():
import { createStore, applyMiddleware } from 'redux';
import FsaThunk from 'fsa-redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(FsaThunk)
);Usage with redux-actions FSA library
Dispatching null initial payload
import { createAction } from 'redux-actions';
const fetchSomeApiSuccess = createAction('FETCH_SOME_API_SUCCESS');
const fetchSomeApiFailure = createAction('FETCH_SOME_API_FAILURE');
const fetchSomeApiRequest = createAction('FETCH_SOME_API_REQUEST', () => dispatch => {
return fetch
.get('some/url')
.catch(err => {
dispatch(fetchSomeApiFailure(err));
throw err;
})
.then(data => dispatch(fetchSomeApiSuccess(data)));
});Calling:
store.dispatch(fetchSomeApiRequest(true));will dispatch an FSA action with this shape first, then will execute the
payload creator function defined as the second argument to createAction:
{ type: 'FETCH_SOME_API_REQUEST', payload: null }Dispatching WITH initial payload
In order to dispatch the initial request action (FETCH_SOME_API_REQUEST in our example),
we must provide the value in the meta field, as follows (the third argument to
createAction):
import { createAction } from 'redux-actions';
const fetchSomeApiSuccess = createAction('FETCH_SOME_API_SUCCESS');
const fetchSomeApiFailure = createAction('FETCH_SOME_API_FAILURE');
const fetchSomeApiRequest = createAction(
// action type
'FETCH_SOME_API_REQUEST',
// payload creator function
payload => dispatch => {
return fetch
.get('some/url')
.catch(err => {
dispatch(fetchSomeApiFailure(err));
throw err;
})
.then(data => dispatch(fetchSomeApiSuccess(data)));
},
// meta creator function
payload => ({ preThunkPayload: payload }),
);Calling:
store.dispatch(fetchSomeApiRequest('foobar'));will dispatch an FSA action with this shape first, then will execute the
payload creator function defined as the second argument to createAction:
{ type: 'FETCH_SOME_API_REQUEST', payload: 'foobar' }License
MIT
