Last active
September 1, 2017 17:14
-
-
Save cqfd/da40b0438b3db51a7e659260482bf3c4 to your computer and use it in GitHub Desktop.
Promisey props
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
// @flow | |
import * as React from 'react' | |
import * as ReactDOM from 'react-dom' | |
import invariant from 'assert' | |
type Props = { | |
onSubmit(comment: string): Promise<void> | |
} | |
type State = { | |
status: 'ready' | 'submitting' | 'failed', | |
comment: string | |
} | |
class CommentSubmit extends React.Component<Props, State> { | |
state = { status: 'ready', comment: '' } | |
render() { | |
return <div> | |
{this.state.status === 'failed' && <p>Bummer, something went wrong!</p>} | |
<input type="text" value={this.state.comment} onChange={this.updateCommentState} /> | |
{this.theSubmitButton()} | |
</div> | |
} | |
theSubmitButton(): React.Node { | |
const status = this.state.status | |
switch (status) { | |
case 'ready': case 'failed': | |
return <button onClick={() => this.submitComment(status)}>Submit!</button> | |
default: | |
return <button>Submitting...</button> | |
} | |
} | |
submitComment = async (status: 'ready' | 'failed') => { | |
this.setState({ status: 'submitting' }) | |
try { | |
await this.props.onSubmit(this.state.comment) | |
this.setState({ status: 'ready', comment: '' }) | |
} catch (e) { | |
this.setState({ status: 'failed' }) | |
} | |
} | |
updateCommentState = (e: SyntheticEvent<HTMLInputElement>) => this.setState({ comment: e.currentTarget.value }) | |
} | |
const sleep = ms => new Promise(awake => setTimeout(awake, ms)) | |
ReactDOM.render( | |
<CommentSubmit onSubmit={async comment => { | |
await sleep(1000) | |
invariant(Math.random() > 0.5, 'Unlucky!') | |
console.log('submitted', comment) | |
}} />, | |
document.getElementById("root") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment