I am using angular version 14, however I am having issues being able to update a value in the ngrx store from a route guard.
the scenario is that once a user has logged in, I call a endpoint which will tell me if their cookie is valid and if so will return their username which I would like to put into the store, because this call is done in the guard I would like to use the data already fetched instead of calling the endpoint a second time on page load.
guard
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isCookieValid().pipe(
map(result => {
if(result?.username == null)
return false;
this.store.dispatch(setUsername({ data: result}))
return true;
}));
}
Reducer
export const authReducer = createReducer(
initialState,
on(setUsername, (state, { data }) => {
return ({
...state,
user: <User>{ username: data.username! },
});
}),
I am not using any effects only using the reducer to set the store value, however the above code results in the route guard being cancelled and called repeatedly forever. I have found that using the same code but changing
this.store.dispatch(setUsername({ data: result}))
to
setTimeout(() => this.store.dispatch(setUsername({ data: result})), 1);
does fix the problem but feels very hacky, any advice would be greatly appreciated