Imrankhan Pathan
Imrankhan Pathan

Reputation: 11

Ngxs Select Decorator return undefined value

The select decorator is always return undefined. I have below state defined.

@State<ISidebarState>({
  name: 'sidebar',
  defaults: {
    moduleWidgetSidebarState: 'close',
    widgetSidebarState: 'close',
  },
})
@Injectable()
export class SidebarState {
  @Selector()
  static getSidebarState(key: string) {
    return createSelector([SidebarState], (state: ISidebarState) => state[key]);
  }

  @Selector()
  static widgetSidebarState(state: ISidebarState) {
    return state.widgetSidebarState;
  }

Injected ngxs module in AppModule.ts

 NgxsModule.forRoot([
      SidebarState,.....

In one of component, When I used the Select decorator select the state. It return undefined.

@Select(SidebarState.widgetSidebarState) sidebarState$: Observable<string>;
ngOnInit(): void {
    console.log(this.sidebarState$, 'widgetSidebarState');

Its working if I used store to select the state.

I am using v 3.8.0 and angular 15.0.1.

I have many states and it always return undefined if I use the select decorator for any states.

Upvotes: 0

Views: 968

Answers (2)

Antoine D
Antoine D

Reputation: 128

I had the same problem. It's a bug that occurs with compilation target ES2022.

I was able to resolve the bug by changing line "target": "ES2022", in my tsconfig.json file to "target": "ES2021",.

Source: Issue GitHub

Upvotes: 1

Cristina Darie
Cristina Darie

Reputation: 91

The selector sidebarState$ is an observable. You need to subscribe to it to start receiving values (but don't forget to usubscribe OnDestroy, otherwise you will get memory leaks) Another option is to use the async pipe in the html file. That way you do not have to remember to unsubscribe.

Upvotes: 0

Related Questions