Last active
July 25, 2017 19:07
-
-
Save MrLeebo/bb6054efa74891ee659a40ccfa244a71 to your computer and use it in GitHub Desktop.
Using async and await to refactor react form components
This file contains 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
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') | |
} | |
} |
This file contains 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
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