Search code examples
angularngxs

NgXs dynamic selector: TypeError: Cannot read property 'x' of undefined


I'm trying to create a NgXs dynamic selector, but I get the runtime error when the selector is used:

TypeError: Cannot read property 'x' of undefined
    at my-state.state.ts:56
    at wrappedSelectorFn (ngxs-store.js:2136)
    at memoized (ngxs-store-internals.js:58)
    at memoized (ngxs-store-internals.js:58)
    at Store.selectSnapshot (ngxs-store.js:2343)
    ...

The selector code:

@State({ ... })
export class MyState {
    @Selector()
    static translations(lng: model.Language) {
        return createSelector([MyState], (state: MyStateModel) => {
            return state.translations[lng];
        });
    }
    ...
}

Solution

  • The reason is the @Selector() decorator, which is intended to be used only with lazy selectors, but not dynamics. I removed the decorator and the problem was solved.

    @State({ ... })
    export class MyState {
        // no decorators here
        static translations(lng: model.Language) {
            return createSelector([MyState], (state: MyStateModel) => {
                return state.translations[lng];
            });
        }
        ...
    }