Benjamin Caure
Benjamin Caure

Reputation: 2403

Persist state using ngrx effect AFTER reducer processing

In my Angular/ngrx app, I'm managing data persistence in indexeddb using @Effect.

  @Effect() updateObj$ = this.actions$
  .ofType(MyActions.UPDATE_OBJ)
  .switchMap( payload => this.storage.set('obj', payload.rawObj));

But this is not what I want: I don't want to persist the raw object from payload, but object transformed by my reducer logic (which is in fact the result state).

Every examples I've seen are very basic so data can be persisted as-is from payload.

I could put this logic in my controller but I don't think it's the redux way to achieve this.

Could you tell me a better way?

Upvotes: 1

Views: 1498

Answers (1)

amu
amu

Reputation: 778

You can access the latest state by using the .withLatestFrom operator.

@Effect() updateObj$ = this.actions$
    .ofType(MyActions.UPDATE_OBJ)
    .withLatestFrom(this.store$.select(<your-state-selector-goes-here>))
    .switchMap( ([action, state]) => ....);

Official .withLatestFrom docs

Simplified docs

Since the effect is triggered by an action dispatch, the state you will receive will be the result state (returned by your reducer handling the UPDATE_OBJ action).

Upvotes: 3

Related Questions