Created
September 30, 2017 13:30
-
-
Save rla/bd30553f0a98ab0e8ba1cb5bf51499fe to your computer and use it in GitHub Desktop.
React form submit
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 SomeForm extends React.Component { | |
// constructor, render() etc are form-specific | |
async submit(e) { | |
e.preventDefault(); | |
const errors = validate(this.state); | |
if (errors.hasError()) { | |
this.setState({ errors: errors.extract() }); | |
return; | |
} | |
try { | |
this.setState({ loading: true }); | |
await (this.id ? this.update() : this.save()); | |
window.scheduleFlash('Order data has been saved.'); | |
window.location = '/orders'; | |
} catch (err) { | |
if (err.json) { | |
if (err.json.errors) { | |
this.setState({ errors: err.json.errors }); | |
} else if (err.json.message) { | |
this.setState({ error: err.json.message }); | |
} | |
} else { | |
window.showSaveError(); | |
throw err; | |
} | |
} finally { | |
this.setState({ loading: false }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment