NGXS: @Snapshot on @Select

Reading your observable state slice in a declarative fashion and instantiating/updating your component property accordingly, so you don’t have to put multiple subscribe blocks in your init function(in case you don’t want to observe it in your template)

Ankit kaushik
2 min readJun 4, 2022

Disclaimer: It might not be a good idea to exhaust this approach in every scenario

Photo by Patrick on Unsplash

Recently, In an imperative programming I’d been seeing this redundant patterns in our application, wherein you want to subscribe to your store state observable or some publisher$ in your component class itself. Suppose there’s a state like:

@Select(UserState) userState$: Observable<UserStateModel>;

For some usecase you might want to subscribe to this State observable and get its value in realtime. Most probably you do something like:

this.userState$.pipe(untilDestroyed(this)).subscribe(() => ...)

But, what if you could delegate this in a declarative fashion to a Typescript decorator. Yes, following goes your decorator implementation:

Now, this decorator could simply be used to retrieve and initialise your component property with the latest value at all the times like:

@Snapshot(tap(console.log)) @Select(UserState) userState: IUserState;@Snapshot<number>(map(x => x + 1)) @Select(UserState.selectedIndex) selectedIdx: number;@Snapshot() @Select(state => state.patient) patient: IPatient;

Furthermore, you can implement similar decorators for your state observables in other state management libraries like NgRx or Akita.

Now, Go on and have fun implementing smart solutions. And don’t forget to like 👏 if you found it helpful.

--

--