The NgRx Effect causing an endless cycle of HTTP requests

I am currently experiencing the following effect:

  initCompaniesAndSetCompanyEffect$: Observable<Action> = createEffect(
    (): Observable<Action> =>
      this.actions$.pipe(
        ofType<changeCompanyActions.InitCompaniesAction>(changeCompanyActions.SelectedCompanyActionTypes.INIT_COMPANY),
        mergeMap(() =>
          this.companyService
            .getCompanies()
            .pipe(
              mergeMap((companies) => [new changeCompanyActions.LoadCompaniesAction(companies), new changeCompanyActions.InitSetCompanyAction(companies[0])])
            )
        )
      )
  );

In addition, these are my defined actions:

export class InitCompaniesAction implements Action {
  readonly type = SelectedCompanyActionTypes.INIT_COMPANY;
}
export class LoadCompaniesAction implements Action {
  readonly type = SelectedCompanyActionTypes.LOAD_COMPANIES;
  constructor(public payload: Company[]) {}
}

export class InitSetCompanyAction implements Action {
  readonly type = SelectedCompanyActionTypes.INIT_COMPANY;
  constructor(public payload: Company) {}
}

Furthermore, when dispatching onInit in my component:

  companies$: Observable<Company[]>;
  selectedCompany$: Observable<Company>;

  constructor(private store: Store<CompanyStoreState.SelectedCompanyState>) {}

  ngOnInit(): void {
    this.companies$ = this.store.select(CompanyStoreSelectors.selectCompaniesList);
    this.selectedCompany$ = this.store.select(CompanyStoreSelectors.selectSelectedCompany);
    this.store.dispatch(new CompanyStoreActions.InitCompaniesAction());
  }

However, I am encountering a problem where multiple http calls are being triggered by the service infinitely. Despite trying various solutions found online, I have not been able to identify the root cause of this issue. If anyone has any insights or suggestions to offer, your help would be greatly appreciated.

Answer №1

Both your InitSetCompanyAction and InitCompaniesAction share the common type

SelectedCompanyActionTypes.INIT_COMPANY

As a result, when the effect triggers, it creates a loop due to the dispatched action having the same type, causing ofType to intercept it.

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

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

How can I access the error stack trace including line numbers from .ts files in a custom error handler in Angular 2?

I want to create a unique error handler for my app by referencing the documentation. However, I am struggling to access the stack trace output from the original ErrorHandler. The reason I need the original output is because the stack trace displayed in the ...

Angular: Turn off animations during the first view rendering / page loading

My Angular 4 component features a list of items. I've implemented the Enter and Leave animations following the guidelines in the Angular documentation (https://angular.io/api/animations/animation), but I'm facing an issue where the animation is t ...

Typescript's Type Specification

I am currently working with NextJs and Typescript and I am facing an issue. Whenever I include the "any" keyword in my code, it renders correctly. However, if I remove it, I encounter errors with post._id, post.title, and post.body. Challenge: Can someon ...

Issues encountered while accessing REST in Angular 6 due to Access-Control-Allow-Origin restrictions

I am currently facing an issue with loading data from a REST source into my Angular 6 app using http: HttpClient from '@angular/common/http'. When I try to call the app in the browser using ng serve --open, it seems like CORS is causing a problem ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

Create a definition file containing a class that can be easily extended

I am attempting to define an interface in a declaration file: declare namespace Foo{ export interface Bar{ new(attrs, options) } } Then I want to inherit from this interface in my code: class Chunk extends Foo.Bar {} However, I encounte ...

An example in Typescript for setting an initial/default value for a data type

Can you create a Type with a default value included? For example: type Animal = { kind : "animal" Legs : number, CanFly: boolean } const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients must initialize the same value `kin ...

What steps can I take to generate a JSON array with this unique format?

The data I received from my angular form is in the array format: [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}]. The data represents a dynamic table with columns for name and number. I need to convert the array above i ...

The JSX component cannot be 'FieldArray' at this time

I'm working on a next.js project and using the Formik component. However, I encountered a type error that says "'FieldArray' cannot be used as a JSX component." Can anyone help me resolve this issue? Here is the error message: 'FieldAr ...

What is the best way to pass data between sibling components using services?

I'm looking to connect a service to a component that can fetch data, share objects, and communicate with other components that are already linked to the database. I've established a service named DashService as follows: import { Injectable } fro ...

Can the ElasticSearch standard Node client be considered secure for integration with cloud functions?

When working with my Typescript cloud functions on GCP, I have been making direct HTTP requests to an ElasticSearch node. However, as my project expands, I am considering switching to the official '@elastic/elasticsearch' package for added conven ...

A guide to customizing cell text color in autoTable using jspdf with Angular2+ based on specific conditions

I am looking to change the text color to red and make it bold if the 'Target Data Type' and 'Data Type Verified' values in the title columns are different when using autoTable in jspdf. I have attempted to write a code for this in Angul ...

What is the best way to define the typings path for tsify?

My TypeScript sources are located in the directory: src/game/ts The configuration file tsconfig.json can be found at: src/game/ts/tsconfig.json Additionally, the typings are stored in: src/game/ts/typings When running tsc with the command: tsc --p s ...

What is the best way to enable external events for Fullcalendar in an Angular environment?

Struggling to integrate external events with Fullcalendar and Angular. Admittedly, I am new to Angular and there are aspects that still elude me. Fullcalendar provides a guide on setting up with Angular, available here. Initially, I managed to set up the ...

Exploring the NextPage type in Next.js

Could someone provide an explanation of the NextPage type within a Next.js TypeScript project? Most sources mention that it is used for type assignment in Next.js, but I am curious about its practical purpose. When and why should we utilize this type? Wha ...

Creating a fresh type in Typescript based on object keys that are already defined within an interface

Here is the scenario I am currently dealing with: interface ListField { code: number; message: string; } interface List { [key: string]: ListField; } export const allCodes: List = { FIRST: { code: 1, message: 'message 1', }, ...

Verify if the Observable (HTTP request) has provided a response, and if not, hold for it?

In my Angular app, I have a calendarComponent that fetches entries from a MongoDB through firebase cloud functions using the calendarService. When creating a new entry, I display an addEventComponent dialog which requires data from the database to function ...

Preventing automatic download and storage of images and videos in an Ionic application

Currently, my chat application allows users to send and receive media such as photos and videos. However, when I open the message page, it automatically downloads and backs up all the media. I am looking to change this functionality on my Ionic page so th ...

Angular and Spring not cooperating with GET request. What's the issue?

I have been working on integrating a simple GET request to send an Object of type SearchMessage from my Spring Boot server to my Angular client application. After running the server application and verifying that the JSON content is correctly displayed at ...