Photo by Fotis Fotopoulos on Unsplash

Bored writing reducers code all over again?

First off I must say how much I like ngxs library. It’s really good for reducing ngrx boilerplate being declarative. I like to reduce imperativeness as much as possible for boring code.

This article covers boilerplate reduction for collections.

Let’s say we’ve got a state with projects.

state.ts:

export interface IProject {

id: string;

name: string;

} export class ProjectsStateModel {

public allProjects: Record<string, IProject>;

public allProjectsLoaded: boolean;

} @State<ProjectsStateModel>({

name: 'projects',

defaults: {

allProjects: {},

allProjectsLoaded: false,

}

})

export class ProjectsState {

All we want to do is to manage the state with actions. We could go like this:

actions.ts:

export class AddProjectAction{

public static type: string = 'AddProjectAction';

constructor(...dummycode)

}

export class EditProjectAction {

public static type: string = 'EditProjectAction';

constructor(...dummycode)

}

... and so on

state.ts”

export class ProjectsState {

... @Action(AddProjectAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: AddProjectAction): void {

...dummy code

} @Action(EditProjectAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: EditProjectAction): void {

...dummy code

} @Action(DeleteProjectAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: DeleteProjectAction): void {

...dummy code

} @Action(UpdateProjectAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: DeleteProjectAction): void {

...dummy code

} @Action(SetProjectsAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: SetProjectsAction): void {

...dummy code

} // and some loading ...

@Action(SetProjectsAction)

public addProjectAction(ctx: StateContext<ProjectsStateModel>, action: SetProjectsAction): void {

...dummy code

}

Doesnt’t look so promising just for managing 1 field.

Now we could invoke those actions in some service

projects-service.ts:

export class ProjectsService{

...

public fetchAllProjects(): Observable<Array<IProject>> {

...some http code

} this.fetchAllProjects().subscribe((projects: Array<IProject>) => {

this.store.dispatch(new SetProjectsAction(projects));

});



but … it gets pretty boring.