Created
May 5, 2016 15:49
-
-
Save raininglemons/2130093a2b6e3f03514bd23ecc49d53b to your computer and use it in GitHub Desktop.
Redux with 'shadow' master model setter / getter.
This file contains 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
import createStore from './redux-shadow'; | |
function reducer (state, action) { | |
switch (action.type) { | |
case 'init': | |
this.setShadow(action.data); | |
return Object.assign({}, this.getShadow()); | |
case 'filter': | |
const filter = action.filter.toLowerCase(); | |
return this.getShadow() | |
.filter(o => o.name.toLowerCase().indexOf(filter) > -1); | |
} | |
} | |
const store = createStore(reducer); | |
/** | |
* Test | |
*/ | |
store.subscribe(() => console.log(store.getState())); | |
/** | |
* Set data | |
*/ | |
console.log('SETTING DATA'); | |
store.dispatch({type: 'init', data: [ | |
{name: 'Abacus'}, | |
{name: 'Aaron'}, | |
{name: 'Dom'}, | |
{name: 'Sergei'} | |
]}); | |
console.log('FILTERING DATA BY `A`'); | |
store.dispatch({ | |
type: 'filter', | |
filter: 'A' | |
}); | |
console.log('FILTERING DATA BY `AA`'); | |
store.dispatch({ | |
type: 'filter', | |
filter: 'AA' | |
}); | |
console.log('UNFILTERED'); | |
store.dispatch({ | |
type: 'filter', | |
filter: '' | |
}); |
This file contains 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
import { createStore } from 'redux'; | |
/** | |
* Wraps the redux store, so that the reducer has access to a persistent | |
* this context. Try not to add things to the `this`, but instead use the | |
* available functions: | |
* - setShadow( data = {} ) | |
* - getShadow( ) | |
* | |
* this.setShadow stores a passed data object out of sight for later retrieval | |
* with this.getShadow(). | |
* | |
* Useful when you have a master data model, and want to return a filtered | |
* / manipulated model in response to various `dispatch` calls. Avoids the | |
* need to cache the original model in a closure. | |
* | |
* @param {Function} reducer | |
* @param {any} [initialState] @see redux docs | |
* @param {Function} enhancer @see redux docs | |
* @returns {Store} | |
*/ | |
function createStoreWithShadow (reducers, initialState, enhancer) { | |
let shadow; | |
const setShadow = (data) => shadow = data; | |
const getShadow = () => shadow; | |
const shadowContext = { | |
getShadow, | |
setShadow | |
}; | |
return createStore(reducers.bind(shadowContext), initialState, enhancer); | |
} | |
export default createStoreWithShadow; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment