Skip to content

Instantly share code, notes, and snippets.

@m4tlch
Forked from lorisleiva/Form.js
Created December 26, 2021 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4tlch/bfcb14218519bbab084b53c804f8a2aa to your computer and use it in GitHub Desktop.
Save m4tlch/bfcb14218519bbab084b53c804f8a2aa to your computer and use it in GitHub Desktop.
// resources/js/services/Form.js
import FormErrors from './FormErrors'
export default class {
constructor (initialData = {}, submitCallback = null) {
this._initialData = initialData
this._submitCallback = submitCallback
this.errors = new FormErrors()
this.reset()
}
reset () {
this.busy = false
this.successful = false
this.errors.clear()
Object.assign(this, this._initialData)
}
async submit (...args) {
if (this.busy || ! this._submitCallback) {
return
}
this.beforeStart()
const result = await this._submitCallback(this, ...args).catch(error => {
this.onFailure(error)
throw error
})
this.onSuccess()
return result
}
export () {
return { ...this }
}
beforeStart () {
this.busy = true
this.successful = false
this.errors.clear()
}
onSuccess () {
this.busy = false
this.successful = true
}
onFailure (error) {
this.busy = false
if (error.response && error.response.data) {
const { errors, message } = error.response.data
this.setErrors(errors, message)
}
}
setErrors (errors, message) {
this.errors.set(errors, message)
}
}
// resources/js/services/FormErrors.js
export default class {
constructor () {
this.errors = {}
this.message = null
}
set (errors, message) {
this.errors = errors || {};
this.message = message || null;
}
has (field) {
return Object.keys(this.errors).includes(field)
}
get (field) {
if (this.has(field)) {
const error = this.errors[field]
return Array.isArray(error) && error.length > 0 ? error[0] : error
}
}
clear (field) {
if (field) {
Vue.delete(this.errors, field);
} else {
this.errors = {}
this.message = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment