DEV Community

Cover image for A New Way of Dispatching Actions With Ngxs for Angular

Posted on • Originally published at Medium

A New Way of Dispatching Actions With Ngxs for Angular

Another fundamental priority in development is trying to limit the use of boilerplates to the minimum. In general, it’d be good practice to keep the code as simple as possible and to avoid verbosity to keep technical debt under control.

For me, there’s nothing more frustrating than a file with hundreds of lines of code, and that’s why I’m always looking for ways to write in a cleaner and clearer way. In this piece, I’ll show you a better way to dispatch actions to an Angular NgXs Store.

The problem

Writing boilerplate code for our state management can be a long process. If we’re working on a complex app with a wide range of operations handled by the Store, we might need tens of different @Select() functions (as well as Action declarations).
When it comes to dispatching actions from our components, we can easily find situations like this below, where we’re dispatching multiple updates to the Store to perform a series of different actions before routing to the success page:

The Solution: Introducing the Dispatch Decorator

@ngxs-labs/dispatch-decorator is another interesting experimental feature for NGXS developed by NGXS Labs.

Even though it’s still not part of the official NGXS package, it’s likely to become an official feature shortly. The package allows us to use the @Dispatch decorator without injecting the Store in the constructor of our component. Moreover, it helps us writing code that is much more compact.

We can install it using the script:
npm i @ngxs-labs/dispatch-decorator

And we can include it in our app.module.ts:

import { NgModule } from '@angular/core';
import { NgxsModule } from '@ngxs/store';
import { NgxsDispatchPluginModule } from '@ngxs-labs/dispatch-decorator';
imports: [
NgxsModule.forRoot(CartState, ProductState),
export class AppModule {}

Now, we’re ready to replace our calls to the Store with the @Dispatch decorator:

import { Dispatch } from '@ngxs-labs/dispatch-decorator';
export class PurchasePageComponent {
@Input() defaultState: any;
constructor() {}
showSuccessPage(): void {
@Dispatch() resetAllStates = () =>[
new ResetAnimationState(this.defaultState),
new ResetPurchaseState(),
new HideHeader(),
new ResetAnswers(),
new ResetCartState(),
new ResetCarouselState(),
new ResetUserState()
@Dispatch goToPage = (route: any) => new RouterGo({path: route});

Much better. Enjoy!

Discussion (0)