Reselect: Question: How do I get state from within the callback of createSelector?

Created on 18 Jun 2016  路  6Comments  路  Source: reduxjs/reselect

I need to call additional selectors from within the selector callback.

Most helpful comment

that way my selector gets called on ANY state change

All 6 comments

Just add state => state as another input selector?

that way my selector gets called on ANY state change

Can you give more info on your specific use case? What's wrong with adding more selectors as input arguments? Why do you need to call selectors _inside_ your new selector?

state structure

state.commands = immutable.Map of id: immutable.Record
state.packages = immutable.Map of id:  immutable.Record
state.package_commands = immutable.Map of packageId: immutable.List of commandIds

so package_commands is a join table

component structure

packages connect(packagesSelector)
    package connect(packageSelector)
        command_list connect(makeFilteredCommandsForPackage)
           command connect(commandSelector)

above the packages page there is a filter which affects both package & 'command_list' components.

package component needs to know if there are any commands which have not been filtered out.

package.cjsx

{makeFilteredCommandsForPackage,
packageFilterSelector,
packageSelector,
} = require '../selectors'

makeMapStateToProps = (state, props)->
  filteredCommandsForPackage = makeFilteredCommandsForPackage()
  (state, props) ->
    commands: filteredCommandsForPackage state, props
    packageFilter: packageFilterSelector state, props
    pack: packageSelector state, props



class Package extends React.Component
  render: ->
    <CommandList commands={ @props.commands } />

module.exports = connect(makeMapStateToProps) Package

selectors.coffee

commandsForPackageSelector = (state, props) ->
  state.package_commands.get props.packageId

# search query to filter by
packageFilterQuerySelector = (state, props) ->
  packageFilterSelector(state).get 'query'

# here "state" is filtering by command's enabled/disabled state
packageFilterStateSelector = (state) ->
  packageFilterSelector(state).get 'state'

makeFilteredCommandsForPackage = ->
  createSelector [
    packageFilterStateSelector,
    _makeFilteredCommandsForPackage()
  ], (filter, commands) ->
    console.log 'filtering state'
    unless filter is 'all'
      return commands.filter (command) ->
        command.enabled is (filter is 'enabled')
    commands

_makeFilteredCommandsForPackage = ->
  createSelector [
     packageFilterQuerySelector,
     commandsForPackageSelector
  ], (query, commands) ->
      commands = commands.filter (commandId) ->
        # this is the problem... I only have the id of the command
        # I need to retrieve the full command here

nevermind. can't avoid subscribing to commands...

Just add state => state as another input selector?

use state as a dependency, will make the selectors expensive!

Was this page helpful?
0 / 5 - 0 ratings