Problem creating a reselection selector that takes a dynamic argument

I am trying to pass a dynamic argument to a reselect selector. The reason for this is that this argument is actually an angular route parameter that is not known in advance. It also cannot be part of the state.

Here is the relevant code from the subscriber that passes the route parameter:

this.store.select(fromRoot.getMessagesWithOtherUserAccount(this.route.params['otherId']))
      .subscribe(messages => this.messagesWithOtherUserAccount = messages);

      

Here is the code for the selectors:

const getMessagesState = (state: State) => state.message.messages;

//See error below... How can I pass my otherId argument here??
const messagesWithOtherUserAccount = createSelector(getMessagesState, messagesWithCounterParty);

export const getMessagesWithOtherUserAccount = (otherId: number) => messagesWithOtherUserAccount(otherId);

....
export const messagesWithCounterParty = (messages: Message[]) => (otherId: number) => withOtherUserAccount(otherId, messages);

      

Here is the error I am getting:

An argument of type 'number' is not assigned to a parameter of type 'State'.

I would like to pass an argument otherId

to messagesWithOtherUserAccount

createSelector

, but I'm not sure how ...

Can anyone please help?

+3


source to share


2 answers


I was able to come up with the following solution:



this.store.select(fromRoot.getMessagesWithCounterParty(this.route.snapshot.params['otherId']))
  .subscribe(messages => this.messagesWithOtherUserAccount = messages);

export const getMessagesWithCounterParty = (otherId: number) => createSelector(getMessagesState, (messages: Message[]) => withOtherUserAccount(otherId, messages));

      

+1


source


createSelector

can create selectors capable of accepting any number of custom / dynamic arguments! See createSelector API .

In your case, the pseudo code to achieve your result could be:



// ...

export const getMessagesWithCounterParty = createSelector(
    getMessagesState,               // Accepts the state as 1st argument
    (otherId: number) => otherId,   // Accepts an Id as 2nd argument

    // Result function
    (messages: Message[], otherId: number) => withOtherUserAccount(messages, otherId),
);

// Later in your application:
getMessagesWithCounterParty(yourState, 42);

      

PS. The error you are getting is not from your application, but from your type checking (probably Typescript).

0


source







All Articles