Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below:

export interface IBookRecords {
    id? : number;
    bookNumber?: string;
    guestID ? : number;
    guestName ? :string;
    bookdetails? : IBookDetail[];
}

export interface IBookDetail {
    id? : number;
    roomName?: string;
    noOfGuest?:number;
}

In action.ts, I wrote the following:

requestSingleRecord : createAction('[Booking] Load booking record'),
requestSingleRecordSuccess : createAction('[Booking] Load booking record', props<{booker: IBookRecords}>())

In effect.ts, I implemented the following:

loadBookRecords1$ = createEffect(() => this.action$.pipe
        (
            ofType(appActions.requestSingleRecord),
            mergeMap(() => 
                this.rmservice.SingleBookRecord()
                    .pipe(
                        switchMap(booker => [
                            appActions.requestSingleRecordSuccess({ booker })])
                    )
            )
        )
    );

In reducer.ts, I defined the state and reducers like so:

export interface IAppState {
    booker : IBookRecords
}
export const initialState: IAppState = {
    booker:{}
}

export const appReducer = createReducer(
    initialState,
    on(appActions.requestSingleRecordSuccess, (state, action) => ({
        ...state, booker :action.booker
    })),

    on(appActions.updaterecord, (state, action) => ({
        ...state,  booker :action.booker
    }))
);

In selector.ts, I created the following selectors:

const selectBookRecordFeature = createFeatureSelector<IAppState>('booker');
export const selectBookRecordCs = createSelector (
    selectBookRecordFeature,
    (state : IAppState) => state.booker
);

However, when I call

this.store.dispatch(appActions.requestSingleRecord());
inside the ngOnInit() function of the app component, it results in an infinite loop.

Any advice would be appreciated.

Thank you

Answer â„–1

Because the action type is the same for both requestSingleRecord and requestSingleRecordSuccess, it creates an infinite loop. To fix this issue, consider changing the action types to something like

   requestSingleRecord : createAction('[Booking] Load booking record'),
   requestSingleRecordSuccess : createAction('[Booking] Load booking record success', props<{booker: IBookRecords}>() )

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

The package information could not be loaded from the registry due to an error: The "timeout" parameter must be in numerical form. Instead, it was received as a string ('100000')

Encountered an issue while trying to install Angular Material in my project: PS C:\Users\Avinash Kumar\Desktop\Projects\CRUD\Project 2\Library Management System\UI\UI\Frontend> ng add @angular/material â ...

Lack of code completion in Nuxt options API when using typescript

After setting up Nuxtjs with typescript, I noticed that there are no code completions in the template and script as expected based on the title. Here is the code: <script lang="ts"> import Vue from 'vue'; import { FeaturedJobs } ...

The Angular template loads and renders even before the dynamic data is fetched

I'm encountering a frustrating issue where the page loads before the data is retrieved. When I log the names in $(document).ready(), everything appears correct without any errors in the console. However, the displayed html remains empty and only shows ...

Creating a custom colored progress bar in Angular 2 using Bootstrap 4

I've been working on implementing a bootstrap progress bar with ng-bootstrap components. The documentation outlines 4 preset coloring options using the directive "type": "success", "info", "warning", or "danger". () To customize the colors, I made ad ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

Error occurred: "Uncaught TypeError: Cannot access 'main' property of an undefined object while attempting to utilize React MuiAlert"

My goal is to create a Redux-based notificator using the example provided in the following link: https://material-ui.com/components/snackbars/#CustomizedSnackbars.tsx This is what I have come up with so far: import { Snackbar } from '@material-ui/co ...

The absence of @angular/forms/FormsModule is causing issues

I am facing an issue with importing the FormsModule from @angular/[email protected] while working with Angular 2 RC5. It seems like a simple task, but I am encountering difficulties. import { FormsModule } from '@angular/forms'; Surprising ...

Adjust the component's input value using a different component

Let's talk about two components in this scenario - HomeComponent and UserComponent. The UserComponent is a child of the HomeComponent and has the following structure: UserComponent.html: <form [formGroup]="form"> <div style="display:block ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

Is it possible to utilize Angular's structural directives within the innerHtml?

Can I insert HTML code with *ngIf and *ngFor directives using the innerHtml property of a DOM element? I'm confused about how Angular handles rendering, so I'm not sure how to accomplish this. I attempted to use Renderer2, but it didn't wor ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...

The NX Monorepo housing a variety of applications with unique design themes all utilizing a single, comprehensive UI component

We are currently working on a design system for a NX monorepo that has the potential to host multiple apps (built using Next.js), all of which will share a common component library. While each app requires its own unique theme, the UI components in the lib ...

Tips for implementing 'transloco' on the 'pie-chart' component in an Angular project

Below is the code snippet: .HTML: <div fxFlex> <ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="single0" ...

Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern. This is my HTML code: ...

Issue with React Native and Redux: Prop values are updating without being called

I'm currently facing a problem with React Native and Redux integration. Using a Redux state to toggle a modal visibility between components seems like the most efficient solution due to its cross-component nature. The modal opens and closes as expec ...

The font awesome symbol is not showing up in the nz-th element

I've encountered an issue with the code snippet below: <th [ngSwitch]="sortIcon" nz-th class="centered" (click)="toggleSortOrder()" nzSort="Stopped">Sort <i *ngSwitchCase="sortEnum.NoSort" class="fa fa-lg fa-fw fa-sort"></i> ...

Node's TypeScript parser loses the order of same name-tags when converting XML to JSON

I've experimented with xml2js and fast-xml-parser and received similar results from both (in different formats, but that's not the focus here) This specific example is from fast-xml-parser Here's the XML data: <test version="1" ...

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...