Last active
May 13, 2018 21:00
-
-
Save rogercbe/f7e1417c31007c9241f52c44e20f53bb to your computer and use it in GitHub Desktop.
Form Object
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
| class Errors { | |
| constructor() { | |
| this.errors = {}; | |
| } | |
| get(field) { | |
| if (this.errors[field]) { | |
| return this.errors[field][0]; | |
| } | |
| } | |
| has(field) { | |
| return this.errors[field]; | |
| } | |
| any() { | |
| return Object.keys(this.errors).lenght > 0; | |
| } | |
| clear(field) { | |
| delete this.errors[field]; | |
| } | |
| fill(errors) { | |
| this.errors = errors; | |
| } | |
| } | |
| export { Errors as default } |
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
| import Errors from './Errors.js'; | |
| class Form { | |
| constructor(fields) { | |
| this.fields = fields; | |
| this.errors = new Errors(); | |
| this.message = ''; | |
| this.processing = false; | |
| } | |
| submit(method, uri) { | |
| this.processing = true; | |
| return new Promise((resolve, reject) => { | |
| axios[method](uri, this.fields) | |
| .then(response => { | |
| this.onSuccess(response.data); | |
| resolve(response.data); | |
| }) | |
| .catch(error => { | |
| this.onFail(error.response.data); | |
| reject(error.response.data) | |
| }); | |
| }); | |
| } | |
| onSuccess(data) { | |
| this.reset(); | |
| this.processing = false; | |
| this.message = data.message; | |
| } | |
| onFail(data) { | |
| this.processing = false; | |
| this.errors.fill(data.errors); | |
| } | |
| reset() { | |
| for (let field in this.fields) { | |
| this.fields[field] = ''; | |
| } | |
| } | |
| } | |
| export { Form as default } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment