redux-smooth-bind-actioncreators
Reduce the boilerplate of "mapStateToProps" and "mapDispatchToProps" !
This implentation of connect / bindActionCreator is a quality of life change for my particular usage. I have more than 1 "store" and each of my pages needs to bind its own actions/states while also binding dispatch. I don't want to include the functions at the bottom of "n" number of pages setting up these connects/bindToActionCreators. So, just include this package and we should be good to go. You now have "actions", and "state", all wrapped up nicely for you and no need to have 2 small functions and includes (at top) on each page.
Please NOTE: This code assumes you have multiple reducers AND you either want to include all of these stores, or just a particular one(or many).
So, in short - the goals is to reduce the boilerplate of "mapStateToProps" and "mapDispatchToProps". If you have these two functions for a file, or two. No worries. But, what if you have 3+ files, that all use this same boilerplate code? Thus, include this npm module -- and boom. One line at the bottom, and you are good to go!
Simple Directions
So, lets make things simple.
- Include the import at top of file
- Write your React class how you wish
- Now, when you export, follow this convention.
- We are assuming ES6
Example In Practice
import * as Actions from 'actions/myactions'
import bindMapComponent from 'redux-map-bind-actioncreators'
class MyReactClass extends Component {
// all your class logic here
}
export default bindMapComponent(MyReactClass)(Actions)
So, in your react class, you can now do 'actions.myFuncName()'. The dispatch is bound to it.
I want my whole state tree on my props. Do nothing, this handles it for you.
I want only 1 (or more) stores on my props. For instance, my "store/state tree" has
the following reducers. Shoes, Prices, Colors, Sizes. BUT, I only want my component to care about the state as it pertains to Shoes & Colors (remember, Shoes is its own reducer )
export default bindMapComponent(MyReactClass)(Actions, "Shoes", "Colors")
// you get:
this.props.state = {
Shoes: {},
Colors: {}
}
I want a custom "actions" name
Now, you see "actions", that is the default return on props. The example above, I assume you destructed it, ala:
const {actions} = this.props
But if you want to denote the 'actions' another way, just do this:
export default bindMapComponent(MyReactClass, "MYACTIONS")(Actions)
In Short:
- default is "actions", you don't have to pass it.
- You want a custom name, pass it in with your class name, as the second arg. now we have: MYACTIONS.myFuncName()
- note: in the examples I use "actions.myFuncName()" or "MYACTIONS.myFuncName()". We assume destructring off of the props.