NGRX effect not saving updated state in store

Viewed 30

I have a boolean setting from our API that we want to cache after it has been called once. Figuring we would need to set the value whenever we added a new instance of appSettings (our application-wide settings), I wrote the following effect:

  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 seems to work in that if the value is already set, it returns the cached data and if the value has not been set, it goes and fetches it from the API. What doesn't seem to work is updating the NGRX store. Even though the returned state has the new values, any future calls to the state just return the original AppSettings and not the one that was produced by the above code.

Am I going about this the right way? Is there some additional call I have to make in order to get the state to reflect the value of the updated currentState property?

1 Answers

You are using ngrx wrong, which might lead to some unexpected sideeffects. Everything in the map operator of isSettingPositive pipe should be handled by a reducer. Never change the state within an effect.

Also, you will never run into the if block.

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

withLatestFrom operator creates you an array of data. Following those lines you wrote

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

That means currentState is an array, where you call isSettingPositiveSet on. That will never be true.

Related