1

I’am trying to refactoring my feature AuthModule Angular6 from NgRX to NGXS.

I’am a problem with a State. Inside there is a Action async:

export const initialState: State = {
  error: null,
  pending: false,
};


@State<State>({
  name: 'login',
  defaults: initialState
})
export class LoginPageState {

  @Selector()
  static error(state: State) {
    return state.error;
  }

  @Selector()
  static pending(state: State) {
    return state.pending;
  }

  constructor(private authService: AuthService) {
  }

  @Action(Login)
  login({getState, patchState, setState, dispatch}: StateContext<State>, {payload}: Login) {

    console.log('login da login page', getState());
    setState({...getState(), pending: true});
    console.log('login da login page', getState());

    return this.authService.login(payload)
      .pipe(
        map((user) => {
          // setTimeout(() => {
          return dispatch([new LoginSuccess({user})]);
          // }, 10);
        }),
        catchError(err => dispatch(new LoginFailure(err))));
  }

  @Action(LoginSuccess)
  loginSuccess({setState, getState}: StateContext<State>) {
    console.log('login success');
    setState({...getState(), error: null, pending: false});
  }

  @Action(LoginFailure)
  loginFailure({setState, getState}: StateContext<State>, {payload}: LoginFailure) {
    setState({...getState(), error: payload, pending: false});
  }

​
}

When I dispatch the Login Action it works but in my redux devtools i get: enter image description here The Login Action is after the LoginSucces Action and if I switch between the stases (@INIT, [Auth] Login Success and [Auth] Login), the sore is always the same. (the pending value should not move?)

If I add a setTimeout function before the call to new dispatch:

 return this.authService.login(payload)
  .pipe(
     map((user) => {
       setTimeout(() => {
         return dispatch([new LoginSuccess({user})]);
       }, 10);
     }),
     catchError(err => dispatch(new LoginFailure(err))));

I get the correct sorting of my actions in devtools and in this case the pending value it moves:

enter image description here

enter image description here

But… where I wrong? I don’t think that this is the correct mode to use the async dispatch!!

Can you help please? Thanks

foralobo
  • 3,947
  • 5
  • 18
  • 17

1 Answers1

1

Currently this is due to the way that NGXS works where a parent action only completes after its child actions have completed. Actions are posted to the dev tools on completion so that they can include the state on completion, this is why you are seeing them coming through in this order.

This is an existing issue on github for this (which will be reopened soon). See this comment in the issue: https://github.com/ngxs/store/issues/139#issuecomment-390673126

Mark Whitfeld
  • 6,500
  • 4
  • 36
  • 32