Reselect: Add state arg for callback of createSelector

Created on 28 Jun 2019  路  2Comments  路  Source: reduxjs/reselect

This is a dupe of another issue #137 that was closed because OP no longer needed the functionality, but hopefully I can make a convincing argument for it.

Here's my simple usecase for selecting recent entries in a basic todo app (minus the memoization you'd expect):

const entryByIdSelector = (state) => state.todos.entrybyId
const recentIdsSelector = (state) => state.todos.recentIds

const entrySelector = (id) => createSelector(
  entryByIdSelector,
  (entryById) => entryById[id]
)

const recentSelector = createSelector(
  recentIdsSelector,
  (ids, __state__) => ids.map( id => entrySelector(id)(__state__) )
)

as you can see in the callback of recentSelector, i need __state__ to call entrySelector.

entrySelector cant be made a selector arg since it takes id whose value comes from the result of another selector arg recentIdsSelector

here my workaround is just to dupe the code from entrySelector

const recentSelector = createSelector(
  recentIdsSelector,
  entryByIdSelector,
  (ids, entryById) => ids.map( id => entryById[id] )
)

this becomes a bit unwieldy esp with more complex selectors.

Most helpful comment

Maybe you can

const entryByIdSelector = (state, id) => state.todos.entrybyId[id]
const entrySelector = createSelector(
  entryByIdSelector,
  (entry) => entry
)

// use
const id = getTodoId()
const entry = useSelector((state) => entrySelector(state, id))

All 2 comments

Maybe you can

const entryByIdSelector = (state, id) => state.todos.entrybyId[id]
const entrySelector = createSelector(
  entryByIdSelector,
  (entry) => entry
)

// use
const id = getTodoId()
const entry = useSelector((state) => entrySelector(state, id))

@taixw2 not sure this will work when id changes and state remains unchanged because of how the selectors are memoized

also how would you implement the recentSelector?

Was this page helpful?
0 / 5 - 0 ratings