Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NgRx - Order of execution of Reducers and Effects

Tags:

angular

ngrx

I have an Angular 8 app which uses NgRx 8.3.0

For one of the actions, I need the reducers to execute before the effects, because the effect depends on the reduced state. Does NgRx guarantee that order, or is there a way to force that order?

like image 863
James Taylor Avatar asked Jan 31 '20 01:01

James Taylor


People also ask

Do effects run after reducers?

Because we know changes to the state are handled by the reducer, we can reasonably conclude that reducers will always run before the effects.

How does NgRx effect work?

Most effects are straightforward: they receive a triggering action, perform a side effect, and return an Observable stream of another action which indicates the result is ready. NgRx effects will then automatically dispatch that action to trigger the reducers and perform a state change.

What does reducer do in NgRx?

Reducers in NgRx are responsible for handling transitions from one state to the next state in your application. Reducer functions handle these transitions by determining which actions to handle based on the action's type.

Is NgRx asynchronous?

The reason for this is NGRX effects are Asynchronous by design. Meaning that the next line that you defined (24) would be triggered immediately after, not once the previous call is completed.


1 Answers

Edit:

NgRx effects fire after all reducers for that action have executed. That order is guaranteed. The reduced state is the payload of your effects.

Found the following comment in lifecycle_hooks.d.ts in the NgRx effects-build project:

By default, effects are merged and subscribed to the store. Implement the OnRunEffects interface to control the lifecycle of the resolved effects.

https://github.com/ngrx/effects-builds/blob/master/src/lifecycle_hooks.d.ts

Effects subscribe to the store and they fire when the state store changes. Because we know changes to the state are handled by the reducer, we can reasonably conclude that reducers will always run before the effects.

Also, found an answer from Brandon Roberts, a Google Developer Expert and a member of the NgRx core team, confirming that the order is guaranteed. https://github.com/ngrx/platform/issues/162

like image 68
Kyler Johnson Avatar answered Sep 27 '22 00:09

Kyler Johnson