Last active
September 1, 2018 10:34
-
-
Save hitsthings/50f61545eb9db8455d4e9d52f15a1a01 to your computer and use it in GitHub Desktop.
Logic outside of React
This file contains hidden or 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
// -- bit excessive for this case, but the example isn't realistic in the first place | |
export const probability = () => Math.random(); | |
// -- some other file | |
export const diceRoll = () => Math.ceil(probability() * 6); | |
// -- some other file | |
export const coinFlip = () => probability() > 0.5 ? 'heads': 'tails'; | |
// -- shared state can be stored however you like (this is just one example) | |
export let wisdom = diceRoll(); | |
const callbacks = []; | |
export const listen = callback => callbacks.push(callback); | |
export const rollForWisdom = () => { | |
wisdom = diceRoll(); | |
callbacks.forEach(cb => cb(wisdom)); | |
}; | |
// -- still consumable in React, or anywhere. Can share state with non-React code too. | |
class Probability extends Component { | |
constructor(props) { | |
super(props); | |
this.state = wisdom; | |
listen(wisdom => this.setState(wisdom)); | |
} | |
render() { | |
return this.props.children({ rerun: rollForWisdom, result: this.state }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment