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

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

A guide to mastering Nested Table creation in Angular

I'm in the process of creating a dynamic table using an array of data let data = [{ "criterialimitId": "3", "criteriaName": "Test", "criteriaId": "1", "criteria": "Max Wager", "type": "DAILY", "oprLimit": "2.5", "status": "1", "acti ...

Error encountered while loading a plugin in Typescript and RequireJS compilation process

Currently, I am working on a Typescript application in Visual Studio 2015 where RequireJS is used for loading modules. I have successfully loaded various modules from .ts classes and external libraries by using their typing .d.ts files. However, I have en ...

Learn the best practices for sharing .env values from the main project component to various reusable npm installed components

In recent projects I've worked on using React and Vue.js, I have utilized .env variables to store API URLs for micro services and other configuration settings that are used throughout the root project. However, when it comes to child components insta ...

How do I specify TypeScript types for function parameters?

I've created a function and used TypeScript to define parameter types: const handleLogin = async ( e: React.FormEvent<EventTarget>, navigate: NavigateFunction, link: string, data: LoginDataType, setError: React.Dispatch<Re ...

Is time-based revalidation in NextJS factored into Vercel's build execution time?

Currently overseeing the staging environment of a substantial project comprising over 50 dynamic pages. These pages undergo time-based revalidation every 5 minutes on Vercel's complimentary tier. In addition, I am tasked with importing data for numer ...

Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process. The TypeScript co ...

"Subpar user interface performance in React due to Redux integration causing

We are currently developing our app using a combination of React and Redux, but we have encountered a performance issue that we need help with. Our main goal right now is to enhance the smoothness of the user interface, as we have noticed some instances wh ...

When adding my Angular web app to the home screen on iOS Safari, the icon appears as a screenshot instead of the specified apple-touch-icon

Despite adding an apple-touch-icon link to my index.html with a 150x150 PNG image, when I try to add my Angular web app as a shortcut to my iOS home screen from Safari, it only appears as a screenshot of the app page. Below is my HTML code: <!doctype ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

SyntaxError: Unexpected token '<' in Angular 6

I have been working on an angular website project. Here is the package.json file for my production environment: "dependencies": { "@angular/animations": "^5.0.2", "@angular/cdk": "^5.1.0", "@angular/common": "^5.0.2", "@angular/compiler": ...