FSA Redux Thunk
Fork of redux-thunk
middleware that enforces
Flux Standard Actions.
Installation
npm install --save redux-thunk
or
yarn add fsa-redux-thunk
Then, to enable Redux Thunk, use applyMiddleware()
:
import { createStore, applyMiddleware } from 'redux';
import FsaThunk from 'fsa-redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(FsaThunk)
);
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(
'FETCH_SOME_API_REQUEST',
payload => dispatch => {
return fetch
.get('some/url')
.catch(err => {
dispatch(fetchSomeApiFailure(err));
throw err;
})
.then(data => dispatch(fetchSomeApiSuccess(data)));
},
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