Endless loop in RxJS when updating the Ngrx store

// Custom Component HTML
<button (click)="reRoute(1)">Select</button>

// Custom Component TypeScript
reRoute(id: any) {
  this.store.select(fromStore.getBasketEntities).subscribe(data => {
     const dynamicUrl = id + '_' + Object.keys(data).length; // dynamically construct new URL
     this.store.dispatch(new fromStore.AddItem(id)); // Add item to store

     // this.router.navigate(['quote/details/' + dynamicUrl], {
     //   queryParams: { type: 'product' }
     // });
  });
}

I am facing an issue where the console output gets stuck in an infinite loop, continuously displaying the dynamicUrl as 1_0, then 1_1, followed by 1_2, and so forth. Each click of the button results in multiple items being added to the store.

My objective is to add an item on each button click while obtaining the current number of items in the store. Initially, the count is 0 and is appended to the item in the store. Consequently, the first item will have an index of 1_0. Subsequent clicks on the button will add items with indexes such as 1_1, 1_2, and so on.

I would greatly appreciate any assistance as this seemingly simple task has consumed several hours of my time.

UPDATE: I switched the dynamicUrl back to id but encountered the same issue. My intention is to navigate to the added item immediately after clicking the button - for instance, the route for the first ever added item should be /details/1_0/. Subsequent routes will involve retrieving the item from the store and displaying its details.

I wanted to provide this additional context to give a comprehensive overview of my objectives. Thank you.

UPDATE_2: I have now moved the dispatch outside of the subscribe function, which resolved the issue of continuously adding items to the store. However, I am still receiving two console logs every time the button is clicked - first displaying 4_0 and then 4_1. I am now considering how to manage the router.navigation.

reRoute(id: any) {
    this.store.select(fromStore.getBasketEntities).subscribe(data => {
        const dynamicUrl = id + '_' + Object.keys(data).length; // dynamically construct new URL
        console.log(dynamicUrl); // debug
        // this.router.navigate(['quote/details/' + dynamicUrl], {
        //   queryParams: { type: 'product' }
        // });
    });
   this.store.dispatch(new fromStore.AddItem(id)); // add item to store
}

Answer №1

When you subscribe to a specific portion of the store state using

this.store.select(fromStore.getBasketEntities)

Each time the basket entities change, the function within the subscribe is triggered. If the AddItem action modifies this part of the store state, it will cause the select to be re-executed.

To handle this, it is recommended to only dispatch the AddItem action when the click event occurs, passing the id as payload. Then, within the reducer function, you can calculate the url accordingly.

reRoute(id: any) {
  this.store.dispatch(new fromStore.AddItem(id));
}

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

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

Looking to dynamically update a date variable based on user selection from a drop-down menu in PHP

I am currently working with a PHP file (index.php) which features a title bar displaying the date in the format (MM YYYY). The dates themselves are extracted from another PHP file named latest_update.php. Within the latest_update file, the dates are specif ...

Typescript is asserting that the React class component has a property, despite what the component itself may suggest

I'm running into an issue with React refs and class components. Here's my simplified code snippet. I have a component called Engine with a property getInfo. In my test, I check for this.activeElement &&, which indicates that it's no ...

What causes special characters to be replaced when using the 'require' function in NodeJS?

I am a beginner in JavaScript and NodeJS, so please be patient with me if this issue seems obvious. The file I have outsourced is a simple config file. Here is an abbreviated version of it: config.js: var config = {}; config.Web = {}; config.Web.Title ...

Is jQuery failing to serialize the form data?

I have a question regarding my form. When I try to serialize it using a jQuery script, the output is empty. Could someone please assist me with this issue? Here is a snippet of my form: <form id="tabb2"> <!-- *************************** ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

Contrast and combine information from two JavaScript arrays of objects

I am struggling with comparing two arrays of objects based on a key. My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target o ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...

Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated. I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating ele ...

Angular: Validation triggered following ngModelChange event

I am dealing with an input field that has a customValidator called fooValidator. This custom validator checks if the input matches a specific regular expression: <form #contratForm="ngForm"> <input type="text" ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

Designing a visual showcase with interactive tab links for image selection

I have been working on developing an Angular component that simulates a tab gallery functionality, inspired by this example. Below is my HTML structure: <div class="gallery-container"> <div class="display-container"> ...

Updating a form field dynamically with AJAX in Laravel

I'm working on updating the field $medic->current based on certain logic that I have in mind. I'm quite new to using AJAX and would appreciate a little guidance to kick things off. In my code, I am calculating the difference between two dates ...

Using jQuery to evaluate multiple conditions within an if statement

I'm working on a script that needs to continuously monitor for the presence of an input field with the class name "email" (as this content is loaded via AJAX). If this input exists, I need to show another input field with the class name of "upload". A ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Turn off the nicescroll scroll bar that appears as a default feature

Is there a way to disable the nicescroll scroll bar that appears in red by default on my html page? It's causing issues with zooming in and breaking the layout. ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...