Laurence
Laurence

Reputation: 7823

ngrx store select always returning undefined

Trying to use ngrx in a project and stuck as store.select always returning undefined. The action seems to be dispatched and I can see the payload has the data. I can see the data even in the Redux DevTools but somehow it never reaches to the controller. I have made a test github repo as there will be too much code to paste here. I have tried many combinations finally given up so really appreciate any help of what i'm doing wrong. I hope someone can help me.

https://github.com/lawphotog/simplest_ngrx

Upvotes: 1

Views: 9758

Answers (1)

John
John

Reputation: 10079

You're trying to return store.photos, but it doesn't look like your store has a photos entry. You set up your store with StoreModule.forRoot({reducer}). And your reducer looks like this

case fromPhotos.PhotosActionTypes.LOAD_PHOTOS_SUCCESS: 
  console.log('payload: ' + JSON.stringify(action.payload))
  return action.payload;
default:
  return state;

And action.payload is an array. So, after you've done fromPhotos.PhotosActionTypes.LOAD_PHOTOS_SUCCESS, your store looks like (I think) :

{
  reducer: []
}

You're trying to get store.photos from the store, which doesn't exist. You should try store.reducer and see what happens.

This all being said, to my eyes, you have a really wonky Store setup. I'd recommend heading over to NGRX and looking through their example app / docs (note, they're in the process of updating their docs for NGRX v5 (which hasn't been released yet), so the docs aren't 100% current). For example, the pattern I've usually seen for stores (not that I'm an expert) is something like

{
  photosReducer: {
    photos: []
  }
}

Then you could select photos with store.select(store => store.photosReducer.photos. Or, the method I use store.select('photosReducer', 'photos'). Also (and maybe this is just because you're experimenting) but your fromPhotos.PhotosActionTypes.LOAD_PHOTOS_SUCCESS action should merge its results into the store (currently, your replacing the entire store with the results). Something like

case fromPhotos.PhotosActionTypes.LOAD_PHOTOS_SUCCESS: 
  console.log('payload: ' + JSON.stringify(action.payload))
  return { 
    ...state,
    photos: action.payload;
  }
default:
  return state;

Upvotes: 3

Related Questions