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:
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:
But… where I wrong? I don’t think that this is the correct mode to use the async dispatch!!
Can you help please? Thanks