Tips on ensuring dispatch is finished before accessing store data. Ngrx dilemma

Is there a way to ensure that a dispatch is completed before selecting from a store? I haven't had any luck finding a solution online. How can I make sure the dispatch finishes before selecting from the store?

I would appreciate any help with my code.

**team-list.component.ts**

 teamsState: Observable<{teams: Team[]}>;

  constructor(private store: Store<fromApp.AppState>) { }

  ngOnInit() {
    this.store.dispatch(new TeamActions.GetTeams({
      search: this.search,
      limit: this.limit,
      skip: this.skip,
      sortBy: this.sortBy
    }));
    this.teamsState = this.store.select('teams');
  }
**team-list.component.html**

<mat-expansion-panel
    *ngFor="let team of (teamsState | async).teams; let i = index">
    <mat-expansion-panel-header>
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-1">{‌{ i+1 }}</div>
          <div class="col-md-1">
              <div class="post-image">
                <img [src]="imageUrl+team.imagePath" [alt]="team.name" style>
              </div>
          </div>
          <div class="col-md-10"> {‌{ team.name }} </div>
        </div>
      </div>
    </mat-expansion-panel-header>
effects
@Effect() // If you do not want to dispatch any actions, if need to modify store state then remove
    teamList = this.actions$.pipe(
        ofType(TeamActions.GET_TEAMS),
            map((action: TeamActions.GetTeams) => {
              return action.payload;
            }),
            switchMap((params: {search: string, limit: number, skip: number, sortBy: string}) => {
                return this.httpClient.get<Team[]>(
                  `${BACKEND_URL}?search=${params.search}&&limit=${params.limit}&&skip=${params.skip}&&sortBy=${params.sortBy}`);
            }),
            map((teams: Team[]) => {
                return {
                    type: TeamActions.SET_TEAMS,
                    payload: teams
                };
            }),
            catchError((err, caught) => {
              // console.log(err.error.errors);
              this.snackBarService.showSnackBar('Unable to Get Teams', true);
              return caught;
            })
        );

When loading for the first time, the dispatching action is not yet completed and the store selection returns as empty. This issue needs to be resolved.

Answer №1

There is no way to wait on a dispatch since it is a fire-and-forget operation.

Fortunately, you can rely on this.store.select('teams'), as it returns an observable. Whenever there is a change in the data, the observable emits a new value, triggering a re-render of your component.

If your list remains empty, you can use @ngrx/store-devtools to verify if your state is being updated properly. If the state is updated but changes are not reflected in the component, ensure that you are creating a new reference to the array instead of modifying it directly.

Answer №2

One helpful strategy is to reset the selector right before dispatching and then apply a filter on the response:

fromApp.GetData.release();
// The current state has been cleared
this.store.dispatch(fromApp.FetchData);
// Previous data values are no longer stored, ensuring only the new desired value is retrieved
this.data = this.store.select(fromApp.GetData).pipe(
    filter(data => !!data)
);

For more information, visit

Answer №3

If you'd like to give it a try, check out the code snippet below.

this.store.dispatch(new TeamActions.GetTeams({
      search: this.search,
      limit: this.limit,
      skip: this.skip,
      sortBy: this.sortBy
    }))
    .subscribe(() => {
        this.teamsState = this.store.select('teams');
    });

This implementation is based on the ngxs state management framework. For more details, visit

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

Locate a subdocument by its unique identifier using the value in the main document

Suppose I have a document with the following structure: { selectedId: ObjectId("57b5fb2d7b41dde99009bc75"), children: [ {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 10}, {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 20}, ...

Why am I encountering a 404 error when trying to install @microsoft/microsoft-graph-client using npm install?

npm install @company/company-graph-client --save npm ERR! code E404 npm ERR! 404 Not Found: @company/company-graph-client@^1.0.0 Running Node v8.9.0 and npm v5.1.0. ...

What is the best way to showcase attributes in HTML using nodejs and expressjs?

I am working on a Node.js and Express application with HTML. In one of my JavaScript files, I use response.render to display an HTML page, passing variables like this: response.render('agent.html', {name: name, phone: phone}); Now, I want to kn ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

Encountering a Compilation Issue in Angular 4

After executing npm install bootstrap@next in my new Angular project, I encountered a compilation error. As a beginner with Angular, I'm seeking assistance on this issue. Compilation Error: ./node_modules/ansi-html/index.js Module build failed: ...

Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component? I have a method in the piechart component that I want to access from the app component using ViewChild. In my piechart.component.ts file: export class PiechartComponent { constructor() ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Is Node JS Suffering from a Memory Leakage Issue?

Currently, I am facing a memory issue with my Node app (v0.8.26) running on Express (v3.4.8). The problem arises when I send an array of objects in the response body through a specific route. This action spikes the Node's memory usage, eventually lead ...

Experiencing difficulties with res.redirect function in Express framework

After numerous attempts to enter my location into the search form, I noticed that while it logs in the console, the res.redirect function fails to take me to a new URL. My goal was to be redirected to a different webpage after submitting my location info ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

Ionic3 attempted lazy loading, however it failed due to the absence of any component factory

When implementing Lazy loading in Ionic3, the browser displays an error message after serving: Error: Failed to navigate - No component factory found for TabsPage. Have you included it in @NgModule.entryComponents? Below is the code snippet: app.modu ...

Encountering a glitch while integrating the angular-select2 module into an Ionic 3 application

Attempting to integrate the angular-select2 npm module into my ionic 3 app. Successfully installed the module using npm within my project Imported the package into my app.module.ts file Added <select2> tags into the html file of my application Enc ...

Issue with Angular2 not able to call POST method in CodeIgniter RESTful API resulting in 404 error

I am encountering an issue with my codeigniter restful API. While the GET method is working fine, I am unable to get the POST method to work from Angular2. this.api.post('quality/addeditquality', this.formdata).subscribe(data => { c ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

Efficiently integrating Firebase Functions with external sub path imports beyond the project's

I encountered an issue in my firebase functions project with typescript. The problem arises when I use types from outside the project with sub path imports, causing the build files to become distorted. Instead of having main:lib/index.js, I have main:lib/ ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

Exploring the possibilities of updating the version dynamically in package.json file

Upon receiving version 1.0.1 (server_version) from the server I make sure process.env.version matches server_version If they are the same, I update process.env.version to server_version. But unfortunately, this process cannot be done from the client side. ...

The Angular 2 routerLink doesn't update the component after the initial click, even though the URL changes in the browser

When using Angular 2, I encountered an issue where clicking a routerLink in the App module successfully navigates to a parameterised route (e.g. /events/2) and loads the correct component (event-details) on the initial click. However, subsequent clicks on ...