Having an issue with loading users into a mat-selection-list within a form. Everything works fine the first time, but upon page refresh, the selector returns 'undefined'.
Initially, both GET_USERS and GET_USERS_SUCCESS are triggered (console log message 'loadUserTest' is displayed), but on refreshing the page, only GET_USERS is executed without any success or console message.
It seems like there is a problem on the refresh as the effect does not run. The error message in the console reads 'ERROR TypeError: Cannot read property 'users' of undefined', which makes sense, as the selector cannot find any data.
Any insights on what might be causing this issue?
Actions
/*--------------GetAllUsers--------------*/
export class GetUsers implements Action {
readonly type = ActionTypes.GET_USERS;
}
export class GetUsersSuccess implements Action {
readonly type = ActionTypes.GET_USERS_SUCCESS;
constructor(public payload: User[]) {}
}
export class GetUsersError implements Action {
readonly type = ActionTypes.GET_USERS_ERROR;
constructor(public payload: string) {}
}
Effect
@Effect()
loadUsers$: Observable<Action> = this.actions$.pipe(
ofType(usersActions.ActionTypes.GET_USERS),
switchMap(() => {
console.log("loadUserTest");
return (
this.userResource.getUsers().pipe(
map((users: User[]) => new usersActions.GetUsersSuccess(users)),
catchError((err) => {
console.log("errorTest");
return of(new usersActions.GetUsersError(err)) }),
)
);
})
);
Reducer
case usersActions.ActionTypes.GET_USERS_SUCCESS: {
return adapter.addAll(action.payload, {
...state,
loading: false,
loaded: true,
});
}
case usersActions.ActionTypes.GET_USERS_ERROR: {
return {
...state,
entities: {},
loading: false,
loaded: false,
error: action.payload,
};
}
Selector
import { createSelector } from '@ngrx/store';
import { AppState } from '../../../core/state';
import { adapter } from './users.adapter';
const { selectAll } = adapter.getSelectors();
export const selectState = (state: AppState) => state.user.users;
export const getUsers = createSelector(selectState, selectAll); //Problem!
Create.ts
ngOnInit() {
this.createEventForm();
this.store$.dispatch(new fromUsers.GetUsers());
this.users$ = this.store$.pipe(select(fromUsers.getUsers));
}
Html
<mat-selection-list class="form-group" #selectedUsers formControlName="users">
<mat-list-option *ngFor="let user of users$ | async" [value]="user">
{{ user.name }}
</mat-list-option>
</mat-selection-list>