create-action-thunk
v1.0.18
Published
You can easly create Redux async actions in React and TypeScript - similar to https://github.com/piotrwitek/typesafe-actions
Downloads
8
Readme
create-action-thunk
You can easly create Redux async actions in React and TypeScript - similar to https://github.com/piotrwitek/typesafe-actions
Table of Contents
Installation
$ npm i --save create-action-thunk
Tutorial
Configuring store
Install redux-thunk
$ npm i --save redux-thunk
Import thunk and configure store
import thunk from 'redux-thunk';
...
createStore(
rootReducer,
initialState,
applyMiddleware(thunk, ...)
);
Creating actions
export const somethingActions = {
loadSomethingSuccess: createAction('LOAD_SOMETHING_SUCCESS', something => ({
type: 'LOAD_SOMETHING_SUCCESS',
payload: something
})),
loadSomething: createActionThunk('LOAD_SOMETHING', dispatch => {
Promise.then(something => {
dispatch(somethingActions.loadSomethingSuccess(something));
}).catch(error => {
throw(error);
});
})
};
// OPTIONAL - creating new action type used by reducer
const returnOfActions = Object.values(somethingActions).map(getReturnOfExpression);
export type SomethingActions = typeof returnOfActions[number];
Creating reducers
export default function somethingReducer(state: SomethingState = initialState.something, action: SomethingActions): SomethingState {
switch (action.type) {
case getType(somethingActions.loadSomethingSuccess):
return action.payload;
case getType(somethingActions.loadSomething):
return state;
default:
return state;
}
}