React Redux & Decorators
Decorators are a great addition to Javascript. For those coding in React, we are already required to use some sort of build process to "transpile" our code from awesomeness to something common browsers will understand. So even if annotations are not an official part of Javascript per-se, it is still very much worth enabling them.
What are decorators?
A simple annotation you can write above your class declarations (and methods too) that modify a class. Some use them to add debugging functionality, others to reduce repetitive code. Decorators are functions under the hood that are executed with the class constructor in scope, so you can make your own with relative ease.
I was surprised to learn that some functions in the React space are already ready for 'decoration'. React-redux's connect and compose function can be used as decorators. Their functionality used traditionally or as decorators is the same: to modify a class and extend functionality. When using React-redux's connect or compose, you are adding properties to the class, whos properties are also connected to redux, reducers and sagas.
Decorators allow us to convert something verbose into something concise.
Above turns into below
Cleaner, but not all too different. The big advantage here comes when you inline your mapStateToProps and mapDispatchToProps. This allows other developers to, first and foremost, see what is being connected.
In my opinion, we have now traded off clean conventional code for a messy declaration at the top of the file with the file. Let's make this even cleaner!
A lot has changed from the last screenshot, and we will go over those changes.
What we now have is something that is clean and concise. We have reduced the possibility of typos by increasing readability and decreasing the code length, variable dependency and created a pattern that is easily reproducible. Each key is added to props as either a selector or a dispatch action. The delimitation between the two are easily discerned from the syntax on line 14 and by an enforced naming convention (setters/fetchers/selectors are prefixed in the name).
The functionality of dispatch is abstracted away to the background, leaving the developer to not worry about the internal requirements for redux. Just pass '@connector' two simple objects and you are done.
Creating the Decorator
To produce this decorator, I created a function that returns a function. The function that is returned is the standard connect() function used for react-redux (which can already be used as a decorator). By creating this function as a wrapper, we are able to mould our parameters into the desired format before passing it along into connect(). This is how we are able to provide such a clean format and enforce the desired shape.
Of course, more could be done in these functions to make the process more hardly and less prone to issues.