Skip to content

Instantly share code, notes, and snippets.

@MrLeebo
Last active July 25, 2017 19:07
Show Gist options
  • Save MrLeebo/bb6054efa74891ee659a40ccfa244a71 to your computer and use it in GitHub Desktop.
Save MrLeebo/bb6054efa74891ee659a40ccfa244a71 to your computer and use it in GitHub Desktop.
Using async and await to refactor react form components
class MyComponent extends Component {
constructor() {
super()
this.handleFormSubmit = this.handleFormSubmit.bind(this)
this.handleCreateSuccess = this.handleCreateSuccess.bind(this)
this.handleCreateError = this.handleCreateError.bind(this)
}
handleFormSubmit(values) {
return this.props.createModel(values)
.then(this.handleCreateSuccess)
.catch(this.handleCreateError)
}
handleCreateSuccess(res) {
this.props.onAdd(res.body)
}
handleCreateError(err) {
toastr.error(err, 'Failure')
}
}
class MyComponent extends Component {
handleFormSubmit = async (values) => {
try {
const { createModel, onCreated } = this.props
const res = await createModel(values)
onCreated(res.body)
} catch (err) {
toastr.error(err, 'Failure')
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment