user256173
user256173

Reputation: 69

Angular NgRx selector cannot read property of undefined

So i need help, trying to figure out my school project example about using NgRx with api services.

I'm getting error in ngrx selector createSelector(), cannot read property of undefined.

Here is StackBlitz : https://stackblitz.com/github/NikolaLukic1/ngrx-example

I guess i messed up something with reducers, or in app.module.ts

Upvotes: 3

Views: 15942

Answers (2)

Mark Bell
Mark Bell

Reputation: 336

I use the safe navigation operator in these scenarios.

export const selectIsVerified = createSelector(
    selectCurrentUser,
    user => user?.emailVerified
)

This way the property won't be read until it is available if indeed, it ever comes available.

Upvotes: 2

Miroslav Maksimovic
Miroslav Maksimovic

Reputation: 549

Your selector was not good. Firstly you have to check whether that state has property called 'posts' and then ask for it, it is a common issue these days.

Here you can find your stackBlitz updated and working.

The code you need is here:

import { createSelector } from '@ngrx/store';

const selectPosts = (state: any) => state.hasOwnProperty('posts') ? state.posts : '';

export const selectedPosts = createSelector(
  selectPosts,
  (state: any) => {
    return state.hasOwnProperty('posts') ? state.posts : '';
  }
);

Upvotes: 4

Related Questions