3

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

Here is the relevant code from the subscribing component 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 get:

Argument of type 'number' is not assignable to parameter of type 'State'.

I would like to pass in the otherId argument to the messagesWithOtherUserAccount createSelector, but I am not sure how...

Can someone please help?

balteo
  • 23,602
  • 63
  • 219
  • 412

2 Answers2

1

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));
balteo
  • 23,602
  • 63
  • 219
  • 412
0

createSelector can create selectors able to accept any number of custom/dynamic arguments! See createSelector API.

In your case the pseudo code to achive your result might 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 get is not from your application but from your type checker (probably Typescript).

Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57