Reputation: 767
I have an Angular 6 app with NgRx and I have problems with how to define actions and state properly.
Actions:
export class LoadUsers implements Action {
readonly type = UserActionTypes.LoadUsers;
constructor(public payload: { pagination: Pagination }) {
}
}
export class LoadUsersSuccess implements Action {
readonly type = UserActionTypes.LoadUsersSuccess;
constructor(public payload: { users: User[], pagination: Pagination}) {
}
}
Pagination interface:
export interface Pagination {
pageSize?: number;
pageIndex?: number;
orderBy?: string;
dir?: string;
filter?: string;
}
State:
export interface State {
pagination: Pagination;
users: User;
}
Reducer:
export function reducer() {
switch (action.type) {
case UserActionTypes.LoadUsersSuccess: {
return {
...state,
pagination: action.payload.pagination,
users: action.payload.users
};
}
}
}
and effects:
@Effect()
loadUsers$ = this.actions$.pipe(
ofType(UserActionTypes.LoadUsers),
map((action: LoadUsers) => action.payload.pagination),
switchMap((pagination: Pagination) => {
return this.usersService.getUsers(pagination).pipe(
map((response: any) => {
const payload = {
users: response.users,
pagination: pagination,
};
return new LoadUsersSuccess(payload);
}),
catchError((error) => of(new LoadUsersFail()))
);
})
);
The problem is for example in the component where I want to display that users from the store. First of all should I dispatch action LoadUsers but for which params? For actual pagination params from the store? But when I subscribe to that, every time it would be modified, LoadUsers action would be dispatched again. Maybe for pagination params from initialState but is it a good approach?
Is it the correct way to implement pagination or should I define actions like ChangePaginationParams() which in reducer assign new pagination params to store and effect of that is loading Users for that new params? But what to do in a situation when the effect will have an error, should it somehow reverse changes in store, because users wouldn't be proper for pagination params in store.
Maybe you can provide me real-world solution, an example of the app where pagination is done using NgRx?
Upvotes: 6
Views: 4855
Reputation: 15505
ChangePaginationParams
seems a better fit in my eyes. If the fetch fails you can undo the ChangePaginationParams
action, e.g. go back one page when the fetch request failed to load the next page.
The initial load would be page 0, 50 items (for example).
Keep in mind that pagination is very subjective to which solution you want to use.
See this GitHub thread for examples.
Upvotes: 1