Skip to content

Instantly share code, notes, and snippets.

@camwest
Last active April 20, 2016 22:11
Show Gist options
  • Save camwest/df472ee7ab0072558b641a253e6a1d7d to your computer and use it in GitHub Desktop.
Save camwest/df472ee7ab0072558b641a253e6a1d7d to your computer and use it in GitHub Desktop.
redux with events
<div>
<MyCollection name="ONE" />
<MyCollection name="TWO" />
</div>
import {load} from './actions';
class MyCollection extends React.Component {
componentDidMount() {
this.props.load(this.props.name);
}
componentDidUpdate(prevProps) {
if(prevProps.name !== this.props.name) {
this.props.load(this.props.name);
}
}
render() {
return (
<div>{this.props.name}: {this.props.value}</div>
)
}
}
function mapStateToProps(state) {
return {
value: state.value
}
}
const mapDispatchToProps = {
loadAndWatch
}
connect(mapStateToProps, mapDispatchToProps)(MyCollection);
import {MyCollection} from '@corp/library';
export function load(name) {
return (dispatch, getState) => {
MyCollection.getValue(name, value => {
dispatch(setValue(name));
})
}
}
export function setValue(name) {
return {
type: 'SET_VALUE',
name
}
}
function reducer(state, action) {
switch(action.type) {
case 'SET_WATCHING':
return Object.assign({}, state, {isWatching: true});
case 'SET_VALUE':
return Object.assign({}, state, {value: action.value});
default:
return state;
}
}
import {setValue} from './actions';
function middleware({dispatch, getState}) {
return next => action => {
switch (action.type) {
case 'SET_VALUE':
next(action);
if (getState().isWatching) {
return;
}
MyCollection.addChangeListener(name, value => {
dispatch(setValue(name))
});
dispatch({type: 'SET_WATCHING'});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment