Skip to content

Instantly share code, notes, and snippets.

@cqfd
Last active January 12, 2017 22:42
Show Gist options
  • Save cqfd/72fc3c1ceb5249ad5b94cf4f98cc46b2 to your computer and use it in GitHub Desktop.
Save cqfd/72fc3c1ceb5249ad5b94cf4f98cc46b2 to your computer and use it in GitHub Desktop.
Using Flow to check state transitions
// @flow
import React, { Component } from 'react'
type State = { s: StartState | EndState }
type StartState = { stage: 'start' }
type EndState = { stage: 'end' }
// c.f. http://stackoverflow.com/questions/41604525/do-flow-refinements-not-propagate-up
export default class App extends React.Component {
state: State = { s: { stage: 'start' } }
render() {
const s = this.state.s
if (s.stage === 'start') {
return <button onClick={this.goToNextStage(s)}>Click me!</button>
} else {
return <p>Nice job!</p>
}
}
goToNextStage = (s: StartState) => () => {
this.setState({ s: { stage: 'end' } })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment