NGXS: @Snapshot on @Select

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store