xreducer
v0.9.1
Published
Create Redux reducers without switch statements or action objects. Less boilerplate, more fun!
Downloads
2
Readme
xReducer
Create Redux Reducers without switch statements or action objects. In short less boilerplate, more fun!
How To Install
yarn add xreducer
xReducer is just a set of javascript functions, and have literally zero hard dependencies! So you can right away use it in any Redux project along with existing reducers. No migration is required!
Why Do I Need This?
Redux is an awesome library, but it makes us write a lot of boilerplate - Action objects, action creators, switch statements..., and other repeating code while connecting the UI components to a Store.
What if we could avoid some of them, and create reducers from a set of simple functions / handlers / actions!?
Using With ReactJs
1. Reducer: Calling createReducer with a map of action handlers, and the initial state; would return a reducer function. You can then use this function with Redux like a conventional reducer.
// Reducer
import { createReducer } from 'xreducer';
const initialState = {
count: 1
};
const reducer = createReducer({
inc: state => ({ count: state.count + 1 }),
dec: state => ({ count: state.count - 1 })
}, initialState);
export default reducer;
2. Connect Component: Use reducer.getActions in place of mapDispatchToProps while connecting, and all the actions will be available under props!
// React Component
import React from 'react';
import { connect } from 'react-redux';
import reducer from './reducer';
class Counter extends React.Component {
render() {
return <p>
{this.props.count}
<button onClick={this.props.inc}>Inc</button>
</p>
}
}
export default connect(state => state, reducer.getActions)(Counter);
Thats it. Isn't that simple!? :sunglasses:
Action Types
xReducer supports 3 types of action handlers. Default is action().
- action((state, payload) => {}, options) - Executes inside the reducer and manages state.
- func((actions, getReducerState, payload, helpers) => {}, options) - Executes outside, for side effects logic without dispatch.
- reduxThunk((actions, getState, payload, helpers) => {}, options) - For side effects logic with dispatch (Needs redux-thunk middleware).
Supported Features
I am trying my best to improve the documentation. But until then, the UTs must give you a sound idea about xReducer APIs and supported features.
Unit Tests for some interesting features:
Contributions & Bug Report
- Do you have an enhancement in mind? Or found a bug? Please create a new issue for the same in xReducer issues page.
- And always, feel free to submit a Pull Request with the changes you would like to see.
License
This project is licensed under the MIT license. See the LICENSE file for more info.