Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 510
user256173 Avatar asked Jan 17 '26 23:01

user256173


2 Answers

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 : '';
  }
);
like image 151
Miroslav Maksimovic Avatar answered Jan 20 '26 13:01

Miroslav Maksimovic


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.

like image 21
Mark Bell Avatar answered Jan 20 '26 11:01

Mark Bell