reselect icon indicating copy to clipboard operation
reselect copied to clipboard

Applying selectors to state instead of props

Open avanderhoorn opened this issue 10 years ago • 2 comments

Most of the samples I have seen of using reselect with redux/react have reselect tying in at the component level - https://github.com/reactjs/reselect#connecting-a-selector-to-the-redux-store. I might be thinking about this the wrong way, but I'm wondering if its advisable/not advisable/ok/not ok to tie selectors in at the reducer/state level so that the computed value is accessible from the state object?

I have a couple of use cases where I have a list of items in an array, and I was wanting to use reselect to "index" these items in various ways (see below), plus filters that need to be applied... In my head it makes sense that these "computed" properties should be available from the state object, but as I've mentioned, this doesn't really fit inline with what I have seen.

Thanks for your help!

// State
{
    // set by reducer
    items: [
        { id: 1, type: 'a', ... },
        { id: 2, type: 'b', ... },
        { id: 3, type: 'a', ... },
        { id: 4, type: 'b', ... }
    ],
    // set by selector
    itemsById: {
        1: { id: 1, type: 'a', ... },
        2: { id: 2, type: 'b', ... },
        3: { id: 3, type: 'a', ... },
        4: { id: 4, type: 'b', ... }
    },
    // set by selector
    itemsBySelector: {
        'a': [ { id: 1, type: 'a', ... }, { id: 3, type: 'a', ... } ],
        'b': [ { id: 2, type: 'b', ... }, { id: 4, type: 'b', ... } ]
    }
}

avanderhoorn avatar May 25 '16 17:05 avanderhoorn

I have one other small question... when a new item comes in (the data is streaming into the app), for the computed properties, I don't what to have to rerun all the data through the various selectors to recompute the output. Currently I compute this incrementally and it feels like that is something I should be able to do here... any thoughts?

avanderhoorn avatar May 25 '16 17:05 avanderhoorn

I've only taken a quick look at this so I might be missing something, but I'm not sure what you gain from also storing the computed data in the store.

If I am understanding your second question correctly, you might want to have a look at reselect-map.

ellbee avatar May 27 '16 07:05 ellbee