Issue with NGRX effect not persisting changes to the state within the store

We have an API boolean setting that we want to cache after the initial call. To achieve this, I created an effect that sets the value when a new instance of appSettings (our application-wide settings) is added:

  public checkCachedEffectg$ = createEffect(()=>
this.actions$.pipe(
  ofType(addAppSettings),
  withLatestFrom(
    this.store.select(selectAppSettings),
    (store)=> store
  ),
  switchMap((currentState)=> {
    if(currentState.isSettingPositiveSet){
      return of(currentState);
    }
    return this.settingsService.isSettingPositive()
      .pipe(map(res => {
        currentState.isSettingPositiveSet = true;
        currentState.isSettingPositive = res;
        return currentState;
      }
    ));
  }),
  map(state => {
    return addAppSettingsSuccess(state);
  }),
  catchError(this.errorHandler.handleError)

The effect appears to be functioning correctly as it returns cached data if the value is already set and fetches it from the API if not. However, there seems to be an issue with updating the NGRX store. Despite having the new values in the returned state, subsequent calls to the state still retrieve the original AppSettings rather than the updated one.

Is my approach correct? Do I need to make an additional call to ensure that the state reflects the updated currentState property value?

Answer №1

You have to be careful with how you're utilizing ngrx, as it could result in unexpected side effects. It's important to handle everything within the map operator of the isSettingPositive pipe using a reducer and avoid changing the state directly within an effect.

Additionally, the if block you've written will never be triggered.

withLatestFrom(
    this.store.select(selectAppSettings),
    (store)=> store
  ),

The withLatestFrom operator generates an array of data for you. Therefore, when you write these lines

switchMap((currentState)=> {
    if(currentState.isSettingPositiveSet){

This implies that currentState is an array on which you are attempting to call isSettingPositiveSet, which will always return false.

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

No contains operator found in Material UI Datagrid

While working on a project, I utilized Material UI's datagrid and successfully implemented filters such as contains and isEmpty. However, I am struggling to find information on how to create a notContains filter. Does Material UI natively support this ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Angular2 routing directs me to a different URL path

In my Angular2 web application, I have set up the following routes: '', '/app', '/login', '/signin', '/validate', '/error', '**': I've defined a route configuration in app.router.t ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Incorporating debounce functionality in React text input using lodash throttle and Typescript

I've been having trouble getting this text input throttle to function properly in my React project, despite spending a considerable amount of time reading documentation. import { throttle } from 'lodash'; ... <input type="t ...

What is causing my click event, which I included in a table row, to not function properly?

I'm having trouble with this code I wrote. When I click on a row in the table (tr tag), nothing happens and I can't figure out why... readDetails(){ this.router.navigate(['/dettaglio-contributivo']); console.log("It should work ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

It is essential for the object to contain a method called '[Symbol.iterator]()' which will yield an iterator upon invocation

Currently, I am facing the following error: error TS2488: Type 'Usuario' must have a '[Symbol.iterator]()' method that returns an iterator. This is my code: usuarios.reducers.ts export interface UsuarioState { users: Usuario[]; ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...

Tips for accessing global variables in an Angular 2 Component

How can I access the Google API library from an Angular 2 module written in Typescript? Whenever I try to access (gapi), it returns undefined. Is there an NPM module available that functions as a Typescript library in Angular 2, or do I need to use the Jav ...

Angular 6 - Use *ngIf to apply the readonly attribute to an input when a certain condition is met

In my current project, I am attempting to set a condition on an input field where if a variable equals 'view', then the readonly attribute should be added to the input. Here is the code snippet I am currently using: <input *ngIf="mode == &ap ...

Having an issue where Firebase Firestore is showing [object, object] instead of the expected document data. What steps should be

I have developed an application that collects user input and uploads it to firebase firestore. However, when I retrieve the documents from firestore to display on another page using a component, it shows [object, object] instead of the actual data. I am ...

Manage sequential observables and await user input

I have a collection of items that I need to loop through in order to determine whether or not a modal dialog should be displayed to the user, and then pause the iteration until the user provides input. The items are stored within an observable as Observabl ...

Navigating through Angular using Typescript can sometimes lead to uncertainty when working with return data. This is where the

How do you handle a request with uncertain data and type checking? For instance, if you are making an HTTP call to an API where various data can be returned, but your component requires a specific data structure defined by an interface. Here's a sim ...

The specified class is not found in the type 'ILineOptions' for fabricjs

Attempting to incorporate the solution provided in this answer for typescript, , regarding creating a Line. The code snippet from the answer includes the following options: var line = new fabric.Line(points, { strokeWidth: 2, fill: '#999999', ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

Extracting data from the Sanity API response in JSON format using Typescript

Struggling with extracting information from a Sanity Client API call and decoding the resulting JSON data. Can someone guide me on how to access specific values? Below is the output of the API call: [ { slug: { current: "test-post", _type: ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...