Last active
October 31, 2016 23:20
-
-
Save casesandberg/e70d77fa808203fa8f74402eb499d247 to your computer and use it in GitHub Desktop.
Auto Scope State to Selectors in Root Reducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
), {}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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