Wednesday, 2 October 2019

filter in createSelector ngrx with props

I'm trying to create a simple selector to get all the messages in the store by a visitor_id, however, what seems so simple to do is always challenging to achieve in ngrx.

I'm using ngrx entity, so I already have the selectAll selector ready, so i tried to do the following:

export const selectMessagesState = createFeatureSelector<MessagesState>('messages');

export const selectAllMessages =  createSelector(
    selectMessagesState,
    fromMessage.selectAll
);

export const selectMessageByVisitorId = createSelector(
    select(selectAll),
    (visitor_id) => map(val => val.filter(c => c.visitor_id == visitor_id))
);

and in the components:


export class Message {
    id: number;
    message: string;
    visitor_id: number;
    is_from_visitor: boolean;
    created_at: string;
}
public messages$ : Observable<Message[]>;

public showThread(visitor: Visitor){

   this.messages$ = this.store.select(selectMessageByVisitorId({ visitor_id: visitor.id}));

However i'm getting Property 'filter' does not exist on type 'unknown' in selectMessageByVisitorId. I'm pretty sure i'm not following the right approach. What I'm trying to do is simple, pass a visitor id to the selectMessageByVisitorId selectir, where it returns the list of messages in the feature store, filtered by the visitor_id.

Update #1

As per @Nikhil suggestion, I changed the selector to :

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(
    select(selectAll),
    messages => messages.filter(val => val.visitor_id == visitor_id)
);

However I'm getting Property 'filter' does not exist on type 'Observable<Message[]>, event though i imported import { filter} from 'rxjs/operators'; (im using ngrx 8.0).

So I though of trying:

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(
    select(selectAll),
    messages => messages.pipe(
            map(val => val.filter(c => c.visitor_id == visitor_id)  ) 
        )
);

but now im getting Type 'Observable<Observable<Message[]>>' is not assignable to type 'Observable<Message[]>'. in the component file this.messages$ = this.store.select(selectMessageByVisitorId({ visitor_id: visitor.id}));



from filter in createSelector ngrx with props

No comments:

Post a Comment