reducer-class
Boilerplate free class-based reducer creator. Built with TypeScript. Works with Redux and NGRX. Has integration with immer.
Heavily inspired by awesome ngrx-actions. It's pretty much a re-write of its reducer-related functionality with stricter typings, usage of reflected typed and leaving aside Angular-only functionality. This library is framework-agnostic and should work with any Redux implementation (Redux, NGRX).
Consider using it with flux-action-class.
- Installation
- Quick start
- Integration with
immer
- Reusing reducers
- Reducer inheritance
- In depth
- How does it compare to ngrx-actions?
Installation
Angular
-
Run
npm i reducer-class immer
-
If you use TypeScript set in you tsconfig.json
"experimentalDecorators": true,"emitDecoratorMetadata": true, -
If you use JavaScript configure your babel to support decorators and class properties
React
-
Run
npm i reducer-class immer reflect-metadata
-
At the top of your project root file (most probably
index.tsx
) add -
If you use TypeScript set in you tsconfig.json
"experimentalDecorators": true,"emitDecoratorMetadata": true, -
If you use JavaScript configure your babel to support decorators and class properties
Quick start
flux-action-class)
Recommended (with
JavaScript version
{} {} {} initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
We can not use
Action
without arguments in JavaScript because there's no compiler which provides us with metadata for type reflection.
Classic NGRX actions
JavaScript version
type = 'ActionCatEat' { thispayload = payload } type = 'ActionCatPlay' { thispayload = payload } type = 'ActionCatBeAwesome' { thispayload = payload } initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
We can not use
Action
without arguments in JavaScript because there's no compiler which provides us with metadata for type reflection.
redux-actions
With
You might have noticed that we always pass actions to
Action
in this version. It's because we no longer use classes for our actions and TypeScript can not provide type metadata.
JavaScript version
const actionCatEat = const actionCatPlay = const actionCatBeAwesome = initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
Old school: action type constants
You might have noticed that we always pass actions to
Action
in this version. It's because we no longer use classes for our actions and TypeScript can not provide type metadata.
JavaScript version
const actionTypeCatEat = 'actionTypeCatEat'const actionTypeCatPlay = 'actionTypeCatPlay'const actionTypeCatBeAwesome = 'actionTypeCatBeAwesome' initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
immer
Integration with If your reducer expects 3 arguments reducer-class
automatically wraps it with produce
from immer.
- Original read-only state
- Draft of the new state that you should mutate
- Action
Why 3? Read pitfall #3 from immer's official documentation.
As you can see we still return
undefined
from the reducer even though we use immer and mutate our draft. Unfortunately, we can not omitreturn
statement here due to how TypeScript handlesvoid
. We can not even writereturn
(withourundefined
), because TypeScript then presumes the method returnsvoid
.
You might have noticed a new import -
Immutable
. It's just a cool name for DeepReadonly type. You don't have to use it. The example above would work just fine if used justIReducerCatState
. Yet it's recommended to wrap it withImmutable
to ensure that you never mutate it.
Actually it makes total sense to use
Immutable
for state of regular reducers as well to make sure you never modify state directly.
Reusing reducers
So what if we want to share some logic between reducers?
Step 1
Create a class with shared logic.
You might have noticed that made this class generic. We have to do that because we do not know what actual state we going to extend, we can only put a constraint on it to make sure it satisfies the structure we need. In other words, if we used
IHungryState
directly and returned{ hungry: true }
(not{ ...state, hungry: true }
) fromhungry
compiler wouldn't complain.
You don't have to use
ReducerClassMixin
class. It's nothing but a convenience wrapper to make sure your class carries an index signature for type-safety. Alternatively you can useIReducerClassConstraint
interface andReducerClassMethod
type.
How to use `IReducerClassConstraint` interface and `ReducerClassMethod` type instead of `ReducerClassMixin` class
JavaScript version
@ { return ...state hungry: true } @ { return ...state hungry: false }
Step 2
Use @Extend decorator.
@Extend can accept as many arguments as you want.
Now our cat reducer uses wasteEnegry
to handle actions ActionCatPlay
, ActionCatBeAwesome
, addEnergy
to handle ActionCatEat
and inherits hugry
and full
methods to handle ActionHungry
and ActionFull
from ReducerHungry
.
JavaScript version
@ initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
How can I make shared reducer's logic dynamic?
You can use class factories.
JavaScript version
const makeReducerHungry = class @ { return ...state hungry: true } @ { return ...state hungry: false } @ initialState = energy: 100 @ { return energy: stateenergy + actionpayload } @ { return energy: stateenergy - actionpayload } const reducer = ReducerCat
Reducer inheritance
Any reducer class is still a class, therefore it can be inherited. It's different way to share some common logic and alter the final behavior for children. There's no runtime information about method visibility (private
, protected
, public
), so if you want to share some common logic without wrapping it with @Action
decorator prefix the shared method with _
.
JavaScript version
initialState = energy: 10 @ { return this } // DO NOT FORGET TO PREFIX IT WITH "_" protected { return energy: stateenergy + actionpayload } // DO NOT FORGET TO PREFIX IT WITH "_" protected { return energy: stateenergy + actionpayload * 10 }
In depth
@Action
?
When can we omit list of actions for You can omit list of actions for @Action
if you want to run a reducer function for a single action. Works with TypeScript only! Action must be a class-based action. It can be a flux-action-class' action, a classic NGRX class-based action or any other class which has either a static property type
or a property type
on the instance of the class.
Running several reducers for the same action
If you have declare several reducer functions corresponding to the same action reducer-class
runs all of them serially. It uses its own implementation of reduce-reducers. The order is defined by Object.keys.
console.logres1.energy // logs 130: 100 - initial value, 10 is added by addEnergy, 10 * 2 is added by addMoreEnergyconsole.logres2 // logs 135: 130 - previous value, 5 is added by addEnergy
How does @Extend work?
It iterates over its arguments and copies their methods and corresponding metadata to a prototype of our target reducer class.
ngrx-actions?
How does it compare to- Stricter typings. Now you'll never forget to add initial state, return a new state from your reducer and accidentally invoke
immer
as a result and etc. @Action
can be used to automatically reflect a corresponding action from the type.ngrx-actions
doesn't allow matching several reducers to the same action, whilereducer-class
allows you to do that and merges them for you.reducer-class
is built with both worlds, Angular and Redux, in mind. It means equal support for all of them!reducer-class
works with function-based action creators and supports redux-actions out-of-the-box.