Unidentified issue arises within the ngrx reducer in Angular4

I am currently facing an issue in my application where I am encountering the following error in a few of my reducers. Upon placing breakpoints on the line causing trouble, there doesn't seem to be any apparent issue, leaving me confused. The error message reads as follows:

ERROR TypeError: undefined is not a function
    at exports.usersUIReducer (usersUI.reducer.ts:14)

Below is the relevant code snippet:

app.module

//Initializing the Angular Object
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        ChartsModule,
        AgmCoreModule.forRoot({
            apiKey: APP_DI_CONFIG.GOOGLE_MAPS_API_KEY
        }),
        StoreModule.provideStore({
            reportExceptionsReducer,
            reportExceptionFormDefaultsReducer,
            reportExceptionsModelReducer,
            reportExceptionUIReducer,
            usersReducer,
            usersUIReducer
        }),
        routing
    ],
.......

UserDashboardComponent.ts

import { Component, OnInit } from "@angular/core";
import { AuthenticationService } from "../../services/authentication.service";
import { UserService } from "../../services/users/user.service";
import { User } from "../../classes/User.class";
import { Store } from "@ngrx/store";
import { CHANGE_USERS_FILTERS, POPULATE_USERS } from "../../state/actions/actions";

@Component({
    selector: 'user-dashboard',
    moduleId: module.id,
    templateUrl: '/app/views/users/users-dashboard.component.html'
})

export class UsersDashboardComponent {
    protected users: Array<User>;
    protected payload: Object;
    protected viewState: Object = {
        usersLoaded: false as boolean
    };
    protected activeUsersConfig: Object = {
        title: 'Users',
        showEdit: true as Boolean,
        showDelete: true as Boolean
    };


    constructor(
       private  _userService: UserService,
       private _authenticationService: AuthenticationService,
       private _store: Store<any>
    ) {
        this._store.select('usersReducer')
            .subscribe((users) => {
                this.users = users;
            });

        this._store.select('usersUIReducer')
            .subscribe((payload) => {
                this.payload = payload;
                if(!this._authenticationService.isSuper()) {
                    this.payload.account = this._authenticationService.accountId
                }
            });

        this.getUsers();
    }


    getUsers(): void {
        this._userService.getUsers(this.payload)
            .subscribe((response) => {
                this._store.dispatch({ type: POPULATE_USERS, payload : {users: response.extras.Users}});
                this.viewState.usersLoaded = true;
                //this.payload.maxItems = response.Users.maxItems;
            });
    }

    paginationChange(pageNum): void {
        this.viewState.usersLoaded = false;
        const offset = pageNum * this.payload.limit;
        this._store.dispatch({ type: CHANGE_USERS_FILTERS, payload: { offset }});
        this.getUsers();
    }
}

and the reducer

import { Action } from "@ngrx/store";
import { CHANGE_USERS_FILTERS } from "../../actions/actions";

const initialState = {
    account: undefined as number,
    limit: 1 as number,
    maxItems: 10 as number,
    offset: 0 as number
};

export const usersUIReducer = (state: any = initialState, action: Action) => {
    switch(action.type) {
        case CHANGE_USERS_FILTERS :
            return Object.assign({}, ...state,
                action.payload
            );
        default :
            return state;
    }
};

Could someone more experienced with ngrx take a look and verify if my implementation is correct? I am struggling to identify the cause of the error and don't know where to begin!

Your help would be greatly appreciated.

Answer №1

This error may be occurring because you have forgotten to export an interface for your State. It also doesn't seem necessary to set account: undefined if you are specifying it as a number.

A possible solution could be:

export interface State {
    account: number,
    limit: number,
    maxItems: number,
    offset: number
}

export const initialState: State = {
    account: 0,
    limit: 1,
    maxItems: 0,
    offset: 0
};

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

Developing interconnected dynamic components in Angular

Can you help me figure out how to create nested dynamic components while maintaining the parent-child relationship? For instance, if I have data structured like this: - A --A.1 --A.2 -B --B.1 -C I want to build components that reflect this structure, su ...

Ways to access or modify variables from a different component in Angular 4 without relying on a service class

Is there a way to interact with or modify variables in another component without using a shared service? I'm dealing with two separate components in my Angular project. Keep in mind that these components are not related as Parent and Child. Compone ...

Guide to routing within the same component in Angular?

In the scenario where I have multiple lists of users with IDs such as (1, 2, 3, 4, 5...), the desired functionality is that upon clicking a button, the details for each respective user should be displayed. For example, clicking on the first user's det ...

Setting the dispatch type in Redux using Typescript

I'm new to typescript and I'm trying to figure out what type should be assigned to the dispatch function. Currently, I am using 'any', but is there a way to map all actions to it? Here's how my code looks like: interface PropType ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Phone Directive causing validation issues in Angular when attempting to paste a value into the control for formatting

In our current project, we are utilizing Angular 17 in conjunction with Reactive forms. A custom directive has been implemented to format the output to the US phone number format `111-222-3333`. However, an issue has arisen where when a number is copied in ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

What is the best way to find the clinic that matches the chosen province?

Whenever I try to choose a province from the dropdown menu in order to view clinics located within that province, an error 'TypeError: termSearch.toLowerCase is not a function' pops up. This part of the code seems confusing to me and any kind of ...

Troubleshooting Angular 2 Component: Why is console.log not functioning in Typescript?

I'm fairly new to both Angular2 and typescript. Given that typescript is a superset of javascript, I assumed that functions like console.log would function as expected. Interestingly, console.log works perfectly in .ts files when placed outside a comp ...

Unlocking the power of global JavaScript variables within an Angular 2 component

Below, you will find a global JavaScript variable that is defined. Note that @Url is an ASP.Net MVC html helper and it will be converted to a string value: <script> var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)'; Sy ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

What steps should I take to allow my code in an AWS Fargate container to take on an IAM role while accessing S3 using Node.js?

I've been working on implementing IAM roles to manage S3 access in my application, but I seem to be missing a crucial step. While running my code in AWS, I encountered a "missing credentials" exception, indicating that something is not configured corr ...

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

Refining Angular service coding techniques

In my application, I have implemented this specific format to interact with an API and retrieve data from it. Below is the code snippet taken from one of the service.ts files: getCheckoutDetails(): Observable<UserDetail> { let query = `7668`; ...

What could be causing the error in Angular Universal Server Side Rendering after deployment on Firebase Hosting?

Currently immersed in Angular development utilizing third-party libraries such as Angular CLI/Angular Universal, following the guidelines laid out here. Also, integrating Firebase hosting and real-time database. The application works flawlessly on my local ...

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

Converting Dates to Strings and Validating Arrays in Nest.js DTOs

Whenever I send a JavaScript Date() object through a put request to my Nest backend, I expect the date format to remain unchanged. However, it gets passed as a string, making it quite challenging to manage. I attempted using DTOs, but encountered an issue ...

Guide on utilizing "setFont" in jsPDF with UTF-8 encoding?

Currently working on a project using Angular 7 I am trying to incorporate a custom font (UTF-8) into my PDF generation service using jsPDF. Despite researching various examples, none seem to work for me. The documentation on the jsPDF GitHub page mentions ...

Has an official Typescript declaration file been created for fabric.js?

Currently, I have come across a Typescript definition for fabric.js on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fabric (https://www.npmjs.com/package/@types/fabric). However, its official status is unclear. Does anyone have more ...

What is the best way to restrict string patterns in TypeScript?

I have a type definition that looks like this: type ActionType = 'TypeA' | 'TypeB' | 'TypeC' | 'TypeD'; I need myActionType to be a string that is either one of the ActionTypes or a combination of ActionTypes separa ...