Subscribing to ngrx store triggers multiple emissions

Currently, I have an app with a ngrx store set up. I am experiencing an issue where, upon clicking a button, the function that fetches data from the store returns multiple copies of the data. Upon subsequent clicks, the number of returned copies grows exponentially.

In my component.ts, the selector connected to the store used to fetch the data looks like this:

this.data$ = this.store.pipe(select(selectors.dataSelector));

The function triggered on click event in my HTML is as follows:

  onClick() {
     this.data$.subscribe(x =>
       console.log(x)
     );
   }

After one iteration:

https://i.stack.imgur.com/9dARp.png

After two:

https://i.stack.imgur.com/yxLRm.png

After three:

https://i.stack.imgur.com/iLVeZ.png

This pattern continues with each click. I am concerned about the impact on performance and wonder why this is occurring. Is there an alternative method to obtain data from the store in the component.ts while ensuring that the data is only retrieved once?

Answer №1

Because each time you click, you are subscribing to data$. If you want to handle this on onClick, consider unsubscribing after logging the value x or utilize rxjs take():

  onClick() {
     this.data$.pipe(take(1)).subscribe(x =>
       console.log(x)
     );
   }

Referencing the documentation:

Benefits of using take()

When you only require a specific number of emissions initially, it is recommended to use take(). For instance, if you wish to determine the first user interaction upon entering a page, subscribe to the click event and retrieve the initial emission.

https://www.learnrxjs.io/operators/filtering/take.html

An alternative recommendation is to subscribe to the store elsewhere, such as in your component constructor:

constructor(store) {
   store.pipe(select(selectors.dataSelector)).subscribe(x => {
       this.componentX = x;
   });
}

Therefore, when clicking, you can access the data like so:

onClick() {
   console.log(this.componentX);
}

This approach ensures that you only subscribe during the component initialization phase.

Additionally, remember to always unsubscribe when the component is destroyed to prevent memory leaks.

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

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

Typescript: Unfiltering a string array

Seeking assistance with TypeScript syntax as a beginner. I'm struggling to refactor this code in order to retrieve the full list of serviceBranches. Currently, there is filtering and mapping resulting in only one serviceBranch being returned from our ...

Encountering deployment problems with React and TypeScript involving router on Github Pages

After successfully running locally, I encountered a 404 error when deploying the website using "npm run deploy." My application is built with React and TypeScript, utilizing react-router-dom BrowserRouter for navigation between pages. I've spent 7 h ...

Angular 6 custom validation: Ensure that at least one textarea is completed

Is there a way for me to display an error message when the submit button is clicked and none of the textarea fields are filled out? And how can I set it up so that the submit action only renders when at least one field is completed? Looking for the best ap ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

I am encountering an issue in Angular where I am trying to add single quotes and a variable to the component.html file

Working with Angular 13, I encountered an issue in my component.html file: The following line functions as expected: <highcharts-chart [constructorType]="'stockChart'"></highcharts-chart> However, when I use a variable: my ...

Troubleshooting issues with exporting Excel in Angular 2

Having trouble exporting data in excel format using JExcelApi lib with an Angular 2 frontend and spring mvc backend? When deploying the backend to Tomcat and making a request via browser, the excel file exports correctly. However, when making the same http ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

Do we need a peer dependency specifically for TypeScript typings or is it optional?

My TypeScript library includes a React component, and one of the optional features allows users to pass an instance of a Redux store as a prop for Redux integration. <Component reduxStore={store}></Component> Since this feature is optional, I ...

What is causing the error message "Module '@reduxjs/toolkit' or its type declarations are not found" to appear?

Although I have a good understanding of React-Redux, I decided to delve into TypeScript for further practice. Following the recommended approach from the react-redux team, I created a new project using the TS template: "npx degit reduxjs/redux-templa ...

``There seems to be an issue with the Angular Material Table dataSource, as it is not binding correctly or updating

When examining the served page: <table _ngcontent-c6="" class="mat-elevation-z8 mat-table" fxfill="" mat-table="" matsort="" role="grid" ng-reflect-data-source="[object Object]"> In View: table matSort fxfill mat-table [dataSource]="dataSou ...

Failure in Dependency Injection in Angular with Typescript

My mobile application utilizes AngularJS for its structure and functionality. Below is the code snippet: /// <reference path="../Scripts/angular.d.ts" /> /// <reference path="testCtrl.ts" /> /// <reference path="testSvc.ts" /> angular.mo ...

Sharing events between disparate components in Angular

Is there a way in Angular to trigger an event within one component and then have another completely unrelated component listen for that event? These components do not share a parent or have any sort of parent-child relationship. I'm trying to find a s ...

Issue with Angular9-MatDatePicker: Unable to establish a connection with 'ngModel' as it is not recognized as a valid attribute of 'input'

Despite my efforts to implement ngmodel binding with matdatepicker, I am still encountering issues, even after reviewing multiple other posts on the topic. Here is a snippet of my HTML: <mat-form-field> <mat-label>Start Date</mat-label ...

Is there a feature in Angular 2+ (specifically Angular 7) that allows for comparing code differences

Is there a code comparison component or plugin available for Angular 2+ (specifically Angular 7) that can compare two separate text files? In our current AngularJS application that we are upgrading, we currently use Ace-Diff and it works effectively. Howe ...

Having trouble selecting all checkboxes in Angular

Having issues with selecting all checkboxes in a populated Angular dataTable. I've tried the code below but it doesn't seem to be working. Can you help me find a solution? Please check out the Stackblitz link for a demo. isChecked = false; checku ...

Angular model remains static when incorporated within the document.addEventListener() attribute

Can anyone help me figure out why my attempt to update the model name this.name on click inside document.getElementById('source-selection').addEventListener is not working? Surprisingly, a simple alert within that function does trigger successful ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

Tips for effectively handling Dependency Injection when interfacing with a service that requires a component

I oversee a project in Angular that follows this specific architecture: ├── media └── src ├── app │   ├── core <-- services folder inside │   ├── data │   ├── layout │  ...