Masquitos
Masquitos

Reputation: 536

Angular 6 ngrx Why selector get object with superfluous property?

I have an selectror export const selectConversations = (state: any): Conversation[] => {.....};

This is store interface

    export interface ChatStore {
    participants: { [key: number]: User };
    conversations: { [key: number]: Conversation };
    messages: { [key: number]: Message };
}   

This is how i register reducer StoreModule.forRoot({ data: chatReducer })

This is reducer

export function chatReducer(state: ChatStore = INITIAL_CHAT_STORE_DATA, action: ChatActions.Actions): ChatStore {...} 

This is function inside my reducer

export function handleLoadCompleteConversations(state: ChatStore, action: LoadCompleteConversations): ChatStore {
    const newStoreState = _.cloneDeep(state);
    newStoreState.conversations = _.keyBy(action.payload, 'id');
    console.log('newStoreState', newStoreState);
    return newStoreState;
}    

The problem is in my selector comes object like

       { data: {
    participants: { [key: number]: User };
    conversations: { [key: number]: Conversation };
    messages: { [key: number]: Message };
}}    

where does property data was added? after all there is no that property inside store interface ChatStore

Upvotes: 2

Views: 250

Answers (2)

rijin
rijin

Reputation: 1759

Because you introduced one more object level by pointing to to 'data'

StoreModule.forRoot({
  data: chatReducer <-- here
})

change to this

StoreModule.forRoot(chatReducer)

You need to modify you selector to select sub state

export const selectConversations = (state: any) => state.conversations;

Using this you need to create your sub-selectors ( giving an example )

export const selectFirstTenConversations = createSelector(
  selectConversations, conversations => conversations.slice(0,10) 
);

Upvotes: 1

jakubm
jakubm

Reputation: 422

You created data property here:

 StoreModule.forRoot({
  data: chatReducer // <----- data points to chatReducer which returns state object.
})

You need to look on chatReducer as a object which it is. If you don't want to have 'data' property then all you need is

 StoreModule.forRoot(chatReducer). 

Upvotes: 1

Related Questions