What is the process for exporting the reducer function and integrating it into the storeModule.forRoot within an Angular application?

Recently, I started delving into ngrx and decided to educate myself by going through the official documentation on their website ngrx.io. During this exploration, I came across a puzzling piece of code in one of their reducers.

The file in question is counter.actions.ts:

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');

Now, let's take a look at the content of counter.reducer.ts:

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);
}

Lastly, we have 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 {}

After reviewing these files, some questions cropped up in my mind:

  1. What exactly does the following snippet do?
export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

present in the reducer file?

  1. Is having counterReducer crucial?

  2. Why not solely export _counterReducer and include it in the storeModule.forRoot within the app module file?

Interestingly, during my research on actions in ngrx, I stumbled upon this explanation:

The exported reducer function is essential due to function call limitations with the View Engine AOT compiler. However, if you opt for the default Ivy AOT compiler (or JIT), it is no longer mandatory.

Could this serve as a plausible rationale?

Answer №1

In my opinion, the code snippet below should suffice without the need for an extra step of re-exporting through another function as it serves no real purpose.

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)
);

Answer №2

1,2). Make sure your reducer exports the reduce method/function and consider exporting it as suggested by @wscttc. You can also include a type for the response if your reducer deals with a more complex object.

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

3). It's important to have feature states as your application expands. Consider having multiple feature states each with their own reducer, effects, and actions for better organization.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

The React state remains stagnant and does not receive any updates

Although there have been numerous questions on this topic before, each one seems to be unique and I haven't found a close match to my specific issue. In my scenario, I have a grid containing draggable ItemComponents. When an item is selected, additio ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

Displaying a dynamic splash screen during the resource-loading process on an Android application

I would like to implement an animated image (currently using a set of PNGs) as a splash screen while my resources are loading. I have successfully displayed the splash screen using this method. However, the issue I am facing is that the splash screen appe ...

Parsing JSON data into different data types in C#

I am looking for a way to transfer various types of data from JavaScript to C#. Specifically, I want to send a JSON object from the JavaScript side using an AJAX call. Here is an example: AnObject = new Object; AnObject.value = anyValue; $.ajax({ typ ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

What is the best way to duplicate several HTML input fields using jQuery?

My div is quite intricate with input fields structured like this <input type="text" name="firstname"> <input type="text" name="lastname"> <input type="text" name="email"> <input type="text" name="address"> <div id="section_toC ...

How can I break down an object with hyphenated key names?

Attempting to perform object destructuring on the following: { name: "Bryan", last-name: "Enid" } However, trying to destructure it like this is not successful: const {name, last-name} = req.body Is there an alternative method to destructure this ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

A step-by-step guide on how to substitute document.write with document.getElementById('ElementID').innerHTML

As someone who is not a programmer, I often find myself attempting to grasp code and make adjustments through trial and error. Currently, I am faced with the challenge of modifying the document.write function in the function pausescroller within a Joomla m ...

What is the most effective method for transferring an error message from the server backend to the vue frontend?

I'm currently working on implementing error handling for a Vue/Vuetify application. The challenge I'm facing involves using external pagination for a datatable that connects to an API with rate limiting restrictions. If users exceed the limit, I ...

What is the best way to add a service to a view component?

I am facing an issue with my layout component where I am trying to inject a service, but it is coming up as undefined in my code snippet below: import {BaseLayout, LogEvent, Layout} from "ts-log-debug"; import {formatLogData} from "@tsed/common/node_modul ...

Changing md-sidenav mode in Angular Material 2

Looking to modify the behavior of the md-sidenav in Angular Material 2, switching from side on desktops to over on mobile devices. Is there a method to achieve this programmatically? Appreciate any guidance! ...

Is there a limit to the number of else if statements I can use? The final else statement

How can I enhance this code snippet? The last else if statement is not working, despite my efforts to fix it. var selectedDntTyp = $("#donationTypDD"); if (selectedDntTyp.length > 0) var DropInitValue = selectedDntTyp.val(); if(DropInitValue == &apos ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

Monitor the latest website address being typed into the browser

Is it possible to track the new URL entered by a user in the browser when they leave the current page using the onunload event? For example, if a user is currently on www.xyz.com/page1.aspx and then types a new URL into the browser, I want to capture that ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

Produce new lines of code using the vscode.window.activeTextEditor.edit method in Visual Studio Code

Hey everyone, I'm currently working on a vscode extension that can automatically generate template code based on the language you are using when you click a button. However, there seems to be an issue with the formatting of the generated code as it do ...

What factors contribute to 'tslib' having more downloads than 'typecrypt'?

How is it possible that 'tslib', a library for 'typescript', has more downloads than 'typescript' itself? If one does not use 'typescript', then they cannot utilize 'tslib' as well. Just because someone us ...