Skip to content

Instantly share code, notes, and snippets.

@distributedlife
Last active February 2, 2017 10:28
Show Gist options
  • Save distributedlife/6aac9bb2664249fc874ea4e6c7964533 to your computer and use it in GitHub Desktop.
Save distributedlife/6aac9bb2664249fc874ea4e6c7964533 to your computer and use it in GitHub Desktop.
A crack at data-driven action dispatch using react(native) and redux
import { makeDataDriven } from './DataDriven';
import { findSpecifiedGameOrLatest, getBowlingTeam, findCurrentInnings } from '../util/queries';
import { setField } from '../actions/field';
import { bowlOver, endOfOver } from '../actions/bowling';
const isAI = (team) => team.type === 'AI';
const mapDispatchToProps = {
setField,
bowlOver,
endOfOver,
};
const mapStateToProps = (state, { gameId }) => {
const game = findSpecifiedGameOrLatest(state.games, gameId);
const bowlingTeam = getBowlingTeam(game);
const currentInnings = findCurrentInnings(game);
return {
aiToSetField: {
when: isAI(bowlingTeam) && !game.currentOver.fieldSet,
dispatch: 'setField',
params: [game, bowlingTeam],
},
aiToBowlOver: {
when: isAI(bowlingTeam) && !game.currentOver.allCardsPlayed,
dispatch: 'bowlOver',
params: [game, bowlingTeam],
},
endOfOver: {
when: currentInnings.ballsRemainingInOver === 0,
dispatch: 'endOfOver',
params: [game],
},
};
};
export default makeDataDriven(mapStateToProps, mapDispatchToProps);
import React from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
export const makeLogicComponent = (componentDidMount) => React.createClass({
render() {
return null;
},
componentDidMount() {
return componentDidMount();
},
});
class DataDriven extends React.Component {
render() {
const { children } = this.props;
const isComponent = (key) => this.props[key].dispatch;
const isVisible = (key) => this.props[key].when;
const render = (key) => {
const dispatch = this.props[this.props[key].dispatch];
const component = makeLogicComponent(() => dispatch(...this.props[key].params));
return React.createElement(component, { key });
};
return (
<View style={{ flex: 1 }}>
{Object.keys(this.props).filter(isComponent).filter(isVisible).map(render)}
{children}
</View>
);
}
}
export const makeDataDriven = (...params) => connect(...params)(DataDriven);
import DataDrivenLogic from './DataDrivenLogic';
import App from './App';
export const AppWrapper = () => (
<DataDrivenLogic>
<App />
</DataDrivenLogic>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment