0.2.3 • Published 8 years ago
redux-module v0.2.3
Redux Module ( Proposal )
Reduced boilerplate for your redux, inspired from Ducks: Redux Reducer Bundles and personally felt the pain of writing too much boilerplate for simple redux apps.
Usage
- Create Redux Module
// sideNav.js
// Simple module that is suppose to open and close SideNavigation (hamburger menu) of an app.
import reduxModule from 'redux-module';
const module = reduxModule({
initialState: {
isSideNavOpen: false
},
reducers: {
openSideNav: (state) => ({ ...state, isSideNavOpen: true }),
closeSideNav: (state) => ({ ...state, isSideNavOpen: false })
}
});
export default module;
- Use it with combineReducers (if multiple reducers)
import { combineReducers } from 'redux';
import { getReducersFromModules } from 'redux-module';
import * as allModules from '/modules/index';
export default combineReducers(getReducersFromModules(allModules));
- Or if you just want to extract reducer from a module
import { getReducerFromModule } from 'redux-module';
const reducer = getReducerFromModule(allModules);
- In your Containers/Components use connect the usual way. redux-modules automatically creates key mirroed actions and to use them just extract actions from your modules like below,
import { connect } from 'react-redux';
import { actions } from 'mobile/modules/appState';
@connect(state => ({ appState: state.appState }))
class App extends Component {
render() {
const { appState, dispatch } = this.props;
return (
<div>
<button onClick={() => dispatch({type: actions.openSideNav})} >Open SideNav</button>
<SideNavigation isSideNavOpen={appState.isSideNavOpen} />
</div>
);
}
}
Where the heck are Actions ?
Redux Modules auto generates mirrored key value actions based on function names provided in reducers
object when creating Redux Module.
For above reducer you will have following actions available,
import { actions } from 'mobile/modules/appState';
console.log(actions); //{ openSideNav: 'openSideNav', closeSideNav: 'closeSideNav' }
You can now use these actions in your usual way ie,
import { actions } from 'mobile/modules/appState';
// somewhere in the component
dispatch({type: actions.openSideNav})