Don’t get me wrong . I love clear and explicit code and don’t like too much “magic”. But I am lazy and do not want to write/copy-paste/generate ton of constructions, which could be easily packed into something much smaller.
Since I have started using Redux I repeat to myself “what a wonderful thing!”. But this wonderful thing requires me to write rather big potion of boilerplate. I know, that Dan Abramov argues very well, that all this staff is really necessary to understand what is happening and that is not a good idea to simplify the general construction. But for me this is an exercise for a few times and after the understanding of the universe finally enters coders head, the code could be suppressed a bit.
So, I did a small helper to reduce my code. Here is, how it could be used:
import { Meteor } from "meteor/meteor"
import collections from "/imports/collections"
import { createReducer } from "meteor-react-helpers" // <-- this is my helper
/* Tags - create reducer only when subscription is ready */
Meteor.subscribe( "tags", {
onReady: () => {
const initialState = {}
collections.Tags.find().fetch().map( tag => { initialState[ tag.name ] = { ...tag, enabled: true } } )
createReducer( "tags", {
add: ( state, tag ) => {
const newItem = {}
newItem[ tag.name ] = { ...tag, enabled: true }
return { ...state, ...newItem }
},
toggle: ( state, tagName ) => {
const tag = state[ tagName ]
if( !tag ) return state
const newItem = {}
newItem[ tagName ] = { ...tag, enabled: !tag.enabled }
return { ...state, ...newItem }
},
}, initialState )
} // <-- This is the default state
} )
/* Keywords filter */
createReducer( "keywords", {
set: ( state, str ) => str || state,
reset: ( state ) => "",
}, "" )
/* Country */
createReducer( "country", {
set: ( state, str ) => str || state,
}, "" )
/* It is possible to add actions into existing reducer later
Maybe it is better to rename helper into 'createOrUpdateReducer'
*/
createReducer( "country", {
reset: ( state ) => "",
}, "" )
Actions, serializable action types are created automatically, new actions added to existing reducers, reducers are combined into one and attached to the only one store, when new reducers are added the combined reducer is replaced with the new one, the redux state is reseted to initial (by default off) when hot-reloading the page - all this is done behind the scene. Actions are namespaced by reducer name and are both exported from the helper and attached to the React context.
https://i.imgur.com/dyEg0bS.png
What do you think about that? Is it just laziness, which leads to the unclear code, or it makes some sense?
Edit: The helper code is here