Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is dispatch not running synchronously within guards on initial load?

Tags:

angular

ngrx

I am seeing that in some specific cases store.dispatch(...) is not executing reducers synchronously like I would have expected. This seems to only happen in CanActivate guards and when the application is first loading.

I've put in console log statements before dispatch (A), in the reducer (B), and after dispatch (C) yet I can clearly see the output (under certain situations) get logged in the order A, C, B. This is happening in nested guards which work something like..

  • Top level guard loads entities and dispatch a LoadAll event to set entities and set a loaded flag in state to true

  • Child guard gets ID from route, checks that record exists in store and selects it by dispatching a Select(id) event

  • Grandchild guard uses selected entity to make some decision

In the guard:

console.log('A');
this.store.dispatch(new fromStore.LoadAllThings(things));
console.log('C');

The reducer:

case ThingActionTypes.LoadAll: {
  console.log('B');
  return adapter.addAll(action.payload, {
    ...state,
    loaded: true,
  });
}

Given the code above I'd expect console output to be A, B C. Instead in certain situations I see A, C, B.

Can someone help explain what is happening here?

like image 403
Kevin Schneider Avatar asked Feb 12 '26 15:02

Kevin Schneider


1 Answers

A dispatch is an async action.

See https://github.com/ngrx/platform/issues/877

like image 135
timdeschryver Avatar answered Feb 15 '26 14:02

timdeschryver