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

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code: <swal #saveSwal title="Are you sure?" text ="Do you want to save changes" cancel ...

Using TypeScript to pass an object's method as an argument in a function call

Recently, I delved into game development using cocos creator with TypeScript/JavaScript, languages that are still new to me. My current challenge involves creating a complex callback method that will trigger methods attached to an array of objects. Here&a ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Angular 5 - Strategies for excluding specific properties from Observable updates

Currently, I am in the process of developing a webpage where users can view and like various videos. The video content and user likes are stored in a database, and I have implemented two Angular services for handling data retrieval and storage. However, I ...

Issue with Typescript and React: Property not found on type 'IntrinsicAttributes'

While working on my app using Meteor, React, and Typescript, I encountered a transpiling error: The property 'gameId' is not recognized in the type 'IntrinsicAttributes & {} & { children?: ReactNode; } In my project, I have a com ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

developing a collection of Material UI text fields

My goal is to construct an accordion containing several textfield mui-components. I have developed a unique render function incorporating all the essential tags and syntax for creating a text field component. Now, I am looking to generate an array of text ...

Issue in Angular Office Add-in: "Unable to locate identifier 'Office'"

After setting up a new Angular project using the angular-cli, I installed the Office TS definitions via npm and added the Office JS API CDN to my index.html header. However, when attempting to call Office.initialize = function(){}; in my main.ts file, it c ...

One issue that may arise is when attempting to use ngOnDestroy in Angular components while rearranging user transitions

Encountered an issue recently with Angular - when the user navigates from component A to component B, component A remains active unless ngOnDestroy is triggered. However, if the user visits component B before going to component A and then leaves, ngOnDes ...

Issue with data updating in Angular rxjs with share, map, and filter functions

After gathering search criteria from a form, I have developed a method that retrieves an observable of talents. fetchTalents(searchCriteria) { return this._allUsers$.pipe( tap((talents) => console.log(talents)), map((tale ...

Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4? This is the Chooser Component import {InputComponent} from './input/input.component' import {BlockComponent} from './block/block.component' export const FormChooser = { Block: Block ...

The issue encountered during the construction of the nrwl library project is that object Object is not recognized as a PostCSS

We are currently facing an issue with our nrwl-nx workspace library project (based on Angular 8) that contains 3-4 angular libraries. While the ng serve function works properly, we have started encountering errors when trying to run ng build my-lib. On ou ...

The text inside the Mapbox GL popup cannot be highlighted or copied

I'm encountering an issue where the text in my popups is unselectable. Even though I can close the popups through various methods, such as clicking on them, the pointer remains as a hand icon when hovering over the text and doesn't change to the ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

An issue arising with the TypeScript antlr4ts listener type

I am currently attempting to incorporate the antlr4 parser into an angular project. Within a dataservice class, there is a function being called that appears as follows: parseRule() { const ruleString = ' STRING TO PARSE'; const inputS ...