Created
February 10, 2016 11:23
-
-
Save slorber/a9540496421f862ea6c0 to your computer and use it in GitHub Desktop.
Using redux-saga + react-redux without Redux
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
// We are integrating our legacy framework (that works a bit like Redux but with a shitty api) | |
// see https://github.com/stample/atom-react | |
// with existing redux tools like Redux-saga and React-redux | |
// Note that Reselect works too | |
// This is an adapter from atom-react store to redux store to be able to use connect() of react-redux | |
// See https://github.com/rackt/react-redux/issues/228 | |
function toReduxStore(atomReactContext) { | |
const onStateChangeListeners = []; | |
atomReactContext.beforeRender(() => { | |
onStateChangeListeners.forEach(listener => listener()); | |
}); | |
return { | |
subscribe: listener => { | |
onStateChangeListeners.push(listener); | |
var isSubscribed = true; | |
return function unsubscribe() { | |
if (!isSubscribed) { | |
return; | |
} | |
isSubscribed = false; | |
var index = onStateChangeListeners.indexOf(listener); | |
onStateChangeListeners.splice(index, 1); | |
} | |
}, | |
dispatch: event => { | |
return atomReactContext.publishEvent(event); | |
}, | |
getState: () => { | |
return atomReactContext.getState(); | |
} | |
} | |
} | |
// We want to be able to use "connect" of react-redux so we use an adapter | |
var reduxStoreLike = toReduxStore(context); | |
var Main = React.createClass({ | |
propTypes: { | |
appStateCursor: AtomReact.PropTypes.isCursor | |
}, | |
render: function() { | |
return ( | |
<ReactReduxProvider store={reduxStoreLike}> | |
<Layout appStateCursor={this.props.appStateCursor}/> | |
</ReactReduxProvider> | |
) | |
} | |
}); | |
const reduxSagaIO = { | |
dispatch: events => context.publishEvents(events), | |
subscribe: listener => { | |
const callback = event => { | |
listener({...event, type: event.name}) | |
}; | |
context.addEventListener(callback); | |
return () => context.removeEventListener(callback); | |
} | |
}; | |
runSaga(saga(),reduxSagaIO,sagaMonitor); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment