Multiple invocations of ngrx effects occur following its return of the value

When the value is returned, ngrx effects are triggered multiple times.

loadMovies$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
        .pipe(
          map(movies => {
             return new counterActions.IncrementCounter();
          }));
      }
    ));
  });

Answer №1

For optimal functionality, it is recommended to include the dispatch: false parameter in your effect definition.

  loadMovies$ = createEffect(() => {
    this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
        .pipe(
          map(movies => {
             return new counterActions.IncrementCounter();
          }));
      }
    )),
    { dispatch: false };
  });

This code snippet is sourced from a relevant document.

  logActions$ = createEffect(() =>
    this.actions$.pipe(
      tap(action => console.log(action))
    ), { dispatch: false });

Answer №2

This problem has cropped up before, and it's a common mistake that often goes unnoticed.

That's why I implemented a new guideline in ngrx-tslint-rules to ensure this error doesn't happen again.

Answer №3

To ensure unique values based on a specific key, you can directly use the operator distinctUntilKeyChanged("<key_name>")

fetchData$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
    ofType(dataActions.DataActionTypes.FetchData),
    distinctUntilKeyChanged("<key_name>"),
    switchMap(() => {
        return this.dataService.fetch()
        .pipe(
          map(data => {
             return new dataActions.UpdateData();
          }));
      }
    ));
  });

Answer №4

Thanks to the createEffect function, I was able to solve my issue by removing the wrapper createEffect function and simply using this.actions$.pipe instead. Now everything is working perfectly.

loadMovies$ = this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
          .pipe(
              map(movies => {
                  return new counterActions.IncrementCounter();
              })
          );
    })
);

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

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Create a data structure with a single key interface that contains a key value pair

Imagine having an interface with just one key and value : interface X { Y : string } It would be great to define a key-value type like this: interface Z { "key" : Y, "value" : string } However, manually doing this can be tedious. What if we ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

Encountering a problem when attempting to start a new project using Ionic3

Currently, I am in the process of setting up a fresh project on my Windows 10 system using Ionic along with all its necessary dependencies and modules fully installed. However, upon executing the following command to create an app: ionic start my-app An ...

Encountering an error while testing Jasmine + Angular with Typescript: "TypeError: 'undefined' is not an object."

I'm having some difficulty while trying to test a specific service. It seems that I am struggling to match the mock response correctly: public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> { return this.testService.g ...

Improving performance in Next.JS by optimizing unused JavaScript resources

Currently working on my first website using Next.js and experiencing poor performance scores after running a lighthouse test. The issue seems to be related to unused JavaScript files located in the chunk folder. I've come across suggestions to split t ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

What is the best way to save geolocation coordinates in a Javascript array?

I am attempting to utilize HTML5 geolocation to determine a user's location and then store the latitude and longitude coordinates in an array for future use with Google Maps and SQL statements. However, when I attempt to add these coordinates to the a ...

Using Typescript's mapped types to apply a single value type to all values across different key types

Having two different key types, OneOf and FeildType, to distinguish between the two types, I initially tried creating the following type but it ended up combining the member types. interface TypeMap { [key: number]: FeildType [key: string]: OneOf } ...

Creating Angular unit test modules

When it comes to creating unit test cases for an Angular app, the application functionality is typically divided into modules based on the requirements. In order to avoid the need for repeated imports in component files, the necessary components, modules, ...

The Content-Type header is missing in the Ajax request for json

In my PHP code, I generate valid JSON and set the content-type header to application/json in my development environment. However, when I deploy this code to an embedded web server, it functions properly but is unable to send the appropriate content-type he ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

Tips for defining data types for spreading properties in TypeScript

I'm grappling with adapting this code to function properly in TypeScript type ScrollProps = { autoHide: boolean autoHideTimeout: number autoHideDuration: number } const renderThumb = ({ style, ...props}) => { const thumbStyle = { borde ...

Navigating with Angular: Every time I refresh the page or enter a specific URL, Angular automatically redirects to the parent route

In my CRM module, I have created a custom Routing Module like this: const routes: Routes = [ { path: 'crm', component: CrmComponent, children: [ { path: '', redirectTo: 'companies', pathMatch: 'full&ap ...

Switching up the Label Colors in Chart.JS

It's been a while since my last question, so please bear with me if I'm not following the rules. I've attached my current code and a reference image of the chart. I am completely new to working with ChartJS. The situation is a bit unique: t ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

The expected rendering of column headers was not achieved following the refactoring of <Column />

After making changes, the header is not rendering properly and I cannot see the "Product ID" header for the column: // DataTable.tsx // React Imports import React, { useState } from 'react'; // PrimeReact Imports import { DataTable as DT } from ...

Is there a way to only retrieve the exception message once within the jQuery each function?

Utilizing the "Tempus Dominus Bootstrap 4" for time manipulation has been a crucial part of my workflow. Recently, I encountered a bug while implementing a function to clear all input values upon clicking a specific button. Unfortunately, the clear funct ...

The code provided creates a web form using HTML and ExpressJS to store submitted information into a MongoDB database. However, there seems to be an issue with the 'post' method, while the 'get' method functions correctly

When I try to submit entries (name, email, address) on localhost:3000 in the browser, the 'post' function is not creating an object in the mongo database even though it works from the postman. The browser displays an error message saying "unable ...

Sort booleans in reverse order in TypeScript in descending order

Having an issue with boolean sorting I have this specific function sortExt() { this.usersChoose.sort(function(a, b) { return a.EXT - b.EXT }) } Triggered by this button <button class="btn btn-info" (click)="sortExt()">Filter</but ...