Skip to content

Instantly share code, notes, and snippets.

@casesandberg
Last active October 31, 2016 23:20
Show Gist options
  • Save casesandberg/e70d77fa808203fa8f74402eb499d247 to your computer and use it in GitHub Desktop.
Save casesandberg/e70d77fa808203fa8f74402eb499d247 to your computer and use it in GitHub Desktop.
Auto Scope State to Selectors in Root Reducer
//reducers/index.js
import { scopeStateToSelectors } from '../helpers/redux'
import threads, { selectors as threadsSelectors } from './threads'
...
// Scopes the state sent down to each of the selector functions by the key:
export const selectors = scopeStateToSelectors({
threads: threadsSelectors,
})
/* ---------- VS ---------- */
import threads, { selectors as threadsSelectors } from './threads'
export const getActiveThread = (state) => threadsSelectors.getActiveThread(state.threads)
export const getThreadByID = (state, id) => threadsSelectors.getThreadByID(state.threads, id)
...n
// helpers/redux.js
import _ from 'lodash'
export const scopeStateToSelectors = (selectorsMap) => {
return _.reduce(selectorsMap, (allScopedSelectors, selectors, scope) => (
_.reduce(selectors, (scopedSelectors, selector, selectorName) => ({
...scopedSelectors,
[selectorName]: (state, ...rest) => selector(state[scope], ...rest),
}), allScopedSelectors)
), {})
}
// reducers/threads.js
...
export const selectors = {
getThreadByID: (state, id) => { // state comes in scoped down to state.threads
return _.find(state.threads, { id })
},
getActiveThread: (state) => { // state comes in scoped down to state.threads
return _.find(state.threads, { id: state.activeThreadID })
},
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment