Skip to content

Instantly share code, notes, and snippets.

@jquense
Last active August 29, 2015 14:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jquense/c9d2d82d3a7f5aa441be to your computer and use it in GitHub Desktop.
Save jquense/c9d2d82d3a7f5aa441be to your computer and use it in GitHub Desktop.
implementation of redux's combineReducers adding flux waitFor()
import { createStore } from 'redux';
import combineReducers from './combineReducers';
let Store = createStore(combineReducers({
reducerA(state = 0, action, waitFor){
if ( action.type === 'TEST'){
waitState = waitFor(waitFor.reducerB)
if ( waitState.reducerB === 5 )
state = 10
}
return state
}
reducerB(state = 5, action, waitFor){
if ( action.type === 'TEST'){
state = 5
}
return state
}
}))
import invariant from 'react/lib/invariant';
import transform from 'lodash/object/transform';
import pick from 'lodash/object/pick';
export default function combineReducers(reducers) {
var tokens = transform(reducers, (obj, _, name) => obj[name] = name)
return function combination(state = {}, action) {
var pendingState = {}
, pending = Object.create(null)
, handled = Object.create(null);
Object.assign(waitFor, tokens);
Object.keys(reducers).forEach( name => {
let reducer = reducers[name];
if (typeof reducer === 'function' && !pending[name]) {
invokeReducer(name)
}
})
return pendingState;
function invokeReducer(name) {
pending[name] = true;
pendingState[name] = reducers[name](state[name], action, waitFor);
handled[name] = true;
}
function waitFor(...names){
names.forEach( name => {
if (pending[name]) {
invariant(handled[name],
`Circular \`waitFor()\` detected while waiting for: ${name}`)
return
}
invariant(reducers[name],
`Attempting to waitFor a reducer that is not loaded: ${name}`)
invokeReducer(name)
})
return pick(pendingState, names)
}
};
}
@tshddx
Copy link

tshddx commented Jul 29, 2015

Looks like a typo on the last waitfor on this line https://gist.github.com/jquense/c9d2d82d3a7f5aa441be#file-app-js-L8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment