Error encountered when dispatching action in ngOnInit: ExpressionChangedAfterItHasBeenCheckedError

I have set up my AppComponent to subscribe to the ngrx store in its constructor:

export class AppComponent {
    submenuItems: Observable<Array<INavigationBarItem>>;

    constructor(private store: Store<AppState>) {
        this.submenuItems = this.store.select<Array<INavigationBarItem>>((state: AppState) => state.submenu.items);
    }
}

In another component, I am dispatching an action within the ngOnInit method like this:

export class SearchPageComponent implements OnInit {
    constructor(private store: Store<AppState>) { }

    ngOnInit(): void {
        this.store.dispatch(new SubmenuAction([
            { title: 'Search', isActive: true },
            { title: 'New Group' }
        ]));
    }
}

This results in the

ExpressionChangedAfterItHasBeenCheckedError
exception. Moving the dispatch call to the constructor of the child component seems to prevent the error, but I'm unsure if this solution is reliable. Placing it inside the constructor body also doesn't seem ideal.

Every component will require a store.dispatch call for generating unique submenu data per page. What is the best way to handle this exception?

Answer №1

After encountering this issue multiple times, it became evident that the root cause lies within Angular's zone management system. To address this, I implemented a workaround that may also prove to be effective in resolving your particular issue:

ngOnInit(): void {
    setTimeout(() => this.store.dispatch(new SubmenuAction([
        { title: 'Search', isActive: true },
        { title: 'New Group' }
    ])), 0);
}

Answer №2

Shifting the dispatch calls to the constructor instead of ngOnInit was the solution that worked for me.

export class SearchPageComponent implements OnInit {
constructor(private store: Store<AppState>) { 
 this.store.dispatch(new SubmenuAction([
        { title: 'Search', isActive: true },
        { title: 'New Group' }
    ]));
}

    ngOnInit(): void { }
}

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

Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error. const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td> ...

Steps for utilizing field labels to transmit values in Protractor

Could someone offer guidance on how to send values using field labels? I understand that it's generally not recommended to use labels for sending values since they can change, but in my case, the labels remain constant. I have attached screenshots of ...

Personalized design for Angular's Material Table (mat-table) in version 2

One way to use the mat-table is by following this element structure: <mat-table> <mat-header-row>...</mat-header-row> <mat-row>...</mat-row> ... <mat-row>...</mat-row> </mat-table> However, if you ...

Tips for effectively utilizing the Ngrx navigation function

While exploring NgRx, I stumbled upon navigation. According to the documentation, it seems like this effect should trigger when the component loads. However, I'm facing an issue where this effect is not getting triggered. Other effects that I've ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

Adjusting the timing of a scheduled meeting

Is there a way for me to update the time of a Subject within my service? I'm considering abstracting this function into a service: date: Date; setTime(hours: number, mins: number, secs: number): void { this.date.setHours(hours); this.date.s ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...

What is the reason behind the failure of a react factory method compilation when extending a typescript class, despite it working perfectly fine on the base class?

As I delve into my lengthy codebase consisting of hundreds of lines, I have managed to narrow down my issue to a concise example. My query pertains to the peculiar behavior exhibited by the Typescript compiler in a specific scenario. The snippet below com ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Iterating through an array with ngFor to display each item based on its index

I'm working with an ngFor loop that iterates through a list of objects known as configs and displays data for each object. In addition to the configs list, I have an array in my TypeScript file that I want to include in the display. This array always ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...

Navigating to a pre-defined default route in Angular 2 with content

Is there a way to set a default route using the updated RC router? @Routes([{ path: '/', component: Home }]) What if I want to display a page with a non-empty path initially? For example: @Routes([{ path: '/home', component: Home } ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

The date format being sent by Angular to Java is incorrect, resulting in the inability to create an object in the

In my coupon system, I am experiencing an issue with the date format. The Java coupon bean has a date.sql startDate and endDate, while the Angular coupon model includes startDate:Date and endDate:Date in its constructor. However, when I display the dates o ...

What is the significance of static constants?

In my TypeScript project, I'm working on creating a constants file that will provide an Opaque token object when ServiceConstants.AUTH_SERVICE_TOKEN is called. I've experimented with two approaches: Using ServiceConstants.ts as a namespace exp ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...