Using Ngrx to filter data following an action dispatch

I have a method for dispatching an action to query and select the account. I am unsure if this is the most efficient approach for selecting the data post-dispatch.

this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));
this.account$ = this._actionsSubject.pipe(
  filter(action => action.type === AccountsApiActions.loadAccountWithDetailsSuccess.type),
  switchMap(() => this._store.select(getAccountDetailById(this._accountId)).pipe(
    tap(account => {
      this.account = account;
      this.accountId = this._accountId;
      this._reportsService.setAccount(account);
    })
  ))
);

Does anyone have suggestions on a better practice for accomplishing this task, or is this method acceptable?

Answer №1

No need to constantly monitor the action dispatches. A well-designed action will automatically update the state and the selector will reflect those changes. Trust the process.

ngOnInit() {
  this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));

  // If you plan to utilize account$ with async pipe
  account$ = this._store.select(getAccountDetailById(this._accountId)).pipe(
    filter(account => !!filter), // omit if no account is received
    tap(account => {
      this.account = account;
      this.accountId = this._accountId;
      this._reportsService.setAccount(account);
    })
  ); // or .subscribe();
}

It's recommended to use effects rather than listening to action dispatches directly in components.

Answer №2

It's essential to include action subject for subscribing to actions in your code. By incorporating the snippet below, you can easily subscribe to actions and have them trigger whenever there is a dispatch of that specific action. Make sure to keep the action subscription in your constructor so you can dispatch the action throughout your component.

Utilize PLUCK to extract the accountId value from the payload

import { Actions, ofType } from '@ngrx/effects';
import { map, pluck, switchMap, tap } from 'rxjs/operators';
...

constructor(private action: Actions) {
 const sub = this.action.pipe(
  ofType(AccountsApiActions.loadAccountWithDetailsSuccess.type),
  pluck('accountId'),
  switchMap((accountId) => this._store.select(getAccountDetailById(accountId)).pipe(
    tap(account => {
     this.account = account;
     this.accountId = this._accountId;
     this._reportsService.setAccount(account);
 }))).subscribe();
  
}

ngOnInit() {
  this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));
}
  

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

Authentication for REST API using JavaScript in the web browser

Currently, I am experimenting with creating a stateless, REST-based API that I intend to use from multiple sources, one of which will be a single-page Javascript web application. The goal is to have a unified API for different clients, even those developed ...

Using Materialize CSS to bind select options in Angular 5 applications

I am currently wrestling with a challenge on my Angular 5 project that utilizes the materialize css framework. Despite trying various fixes suggested in other resources, I still can't seem to resolve the issue related to select/options functionality. ...

Issue with automatic updating of table

One challenge I am facing involves the index.php file, which displays data in tables from a loop: $sql = 'SELECT id FROM usertbl'; $stmt = $hund->runQuery($sql); $stmt->execute(); $row = $stmt->fetchALL(PDO::FETCH_ASSOC); <?php fore ...

Adding data and consolidating MongoDB records

I'm currently immersed in working with mongoose ODM and MongoDB. I've encountered a minor hiccup that I can't quite figure out. In my User collection, I have the following schema: const userSchema = new Schema({ name: String, posts: [{type ...

Accessing a JSON file over a network using JavaScript

Struggling to access a basic data file using JavaScript, and it's proving to be quite challenging. The file will be hosted on a remote server and ideally accessed via HTTP. While I'm new to JavaScript, I've come across JSONP as a potential s ...

`Need to clean parameters for safe use in JavaScript code?`

I am working with the php code below: <?php $redirect_lp = $_GET['lp']; ?> <script> setTimeout(function(){ window.location.href = "<?php echo $redirect_lp; ?>"; }, 10) </script> How can I properly sanitiz ...

The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code: var userId = req.params.UserId const m ...

Styling select input forms with Bootstrap 3

I'm looking to create a select dropdown menu that matches the style of other inputs in a bootstrap 3 form. You can view an example of what I want to achieve on this plunker or see the image below: This CSS code is included in the header: <!-- Boo ...

Encountering issues with accessing 'this' items in the confirmation function of Angular Material's $mdDialog

Attempting to utilize the confirm function within an Angular Material $mdDialog in order to clear an array and then log it to the console is proving problematic. There appears to be an issue with accessing 'this' objects, arrays, expressions, and ...

The website functions perfectly on a local server, but encounters issues when compiled using the npx vite build command

As I work on building my website, I've come across a deployment issue that's causing quite the headache. Following the documentation for Vite and three.js found here, I successfully installed both tools and completed my site. However, running npx ...

Guide on how to include a parent key in JSON within a React application

In my current web application setup, I am using Rails as the backend and React as the frontend. The data entered by users in HTML forms is transmitted between the applications in JSON format. However, there seems to be an issue with the format of the JSON ...

The Observable in Redux does not seem to refresh after a change in state

Our current setup involves Angular 6 and Redux. When initializing one of the components, the process looks like this: ngOnInit() { this.parameterActions.loadParameters(); this.principleActions.loadPrinciples(); this.domainPrincipleActions.loa ...

Finding the filename using the event object in JavaScript: A step-by-step guide

Picture this scenario: an HTML file named page1.html includes a script tag for base.js. Within base.js (an external JavaScript file), I assign an onclick listener to a button that exists in page1.html. This base.js file is also included in script tags on o ...

Incorporating Flash videos into an Angular HTML partial using AngularJS techniques

I've been struggling to embed a flash game in an angular HTML partial. The game loads without errors, but when I right click on the blank flash screen, it says "movie not loaded." I have tried using https://github.com/Pleasurazy/angularjs-media and an ...

Update the state by utilizing the File's onLoad function

I've been facing some challenges while trying to set the state using FileReader's onLoad function. My objective is to display multiple images and update the state accordingly. Despite extensively researching various stackoverflow threads and mak ...

I am experiencing issues with my Vue.js application when trying to send an HTTP POST request

I am encountering an issue in my Vuejs application while trying to send an HTTP POST request to my server. The error message that keeps popping up in the console is: TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.post is not a function at Object ...

What is the best way to combine two objects in Angular?

How can I merge objects in Angular 2? Object Response 1 0:Object 1:Object 2:Object 3:Object Object Response 2 0:Object 1:Object 2:Object 3:Object MyComponent Component resultdata :any=Array; fooddrinks_data_func(Defaultparams){ return this.Ci ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Is there a way to compare the attributes of two objects to see if they are similar, except for one attribute?

Looking at the two objects below, my goal is to compare their attributes (name, modifiers, price) for equality without considering one particular attribute (quantity). For instance, in the scenario given, if I were to compare Object A and Object B, they w ...