Search code examples
javascriptangulartypescriptngrx

How to export the reducer function and add it to the storeModule.forRoot in Angular?


I am new to ngrx and am reading the ngrx documentation from their website ngrx.io. I stumbled upon some code in their reducer and i dont understand it.

This is the counter.actions.ts file

import { createAction } from '@ngrx/store';

export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');

This is the counter.reducer.ts file.

import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
 
export const initialState = 0;
 
const _counterReducer = createReducer(
  initialState,
  on(increment, (state) => state + 1),
  on(decrement, (state) => state - 1),
  on(reset, (state) => 0)
);
 
export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

This is the app module file


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
 
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
 
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, StoreModule.forRoot({ count: counterReducer })],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

My question are as follows:

  1. What is
export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

in the reducer file?

  1. Is counterReducer neccessary?

  2. Why not just export _counterReducer alone and add it to the storeModule.forRoot in the app module file.

I saw these while reading about action in ngrx website

The exported reducer function is necessary as function calls are not supported the View Engine AOT compiler. It is no longer required if you use the default Ivy AOT compiler (or JIT).

Is this a possible explanation?.


Solution

  • I believe the following would work, there is not real point to have that additional step of re-exporting through another function as that doesnt really do anything.

    import { createReducer, on } from '@ngrx/store';
    import { increment, decrement, reset } from './counter.actions';
     
    export const initialState = 0;
     
    const counterReducer = createReducer(
      initialState,
      on(increment, (state) => state + 1),
      on(decrement, (state) => state - 1),
      on(reset, (state) => 0)
    );