axios-form-handler
Version:
A form handling library inspired by Inertia.js useForm, with Axios integration and Laravel validation support
122 lines (118 loc) • 3.63 kB
JavaScript
'use strict';
var axios = require('axios');
class Form {
constructor(fields) {
this._initialData = {};
this._fields = {};
this.errors = {};
this.processing = false;
this._initialData = Object.assign({}, fields);
this._fields = { ...fields };
// Expose each field as a direct enumerable property (no custom Proxy)
for (const key of Object.keys(this._fields)) {
this[key] = this._fields[key];
this.errors[key] = null;
Object.defineProperty(this, key, {
get() {
return this._fields[key];
},
set(value) {
this._fields[key] = value;
if (Object.prototype.hasOwnProperty.call(this.errors, key)) {
delete this.errors[key];
}
},
enumerable: true,
configurable: true,
});
}
}
static setAxiosInstance(axiosInstance) {
Form.http = axiosInstance;
}
get fields() {
return this._fields;
}
get hasErrors() {
return Object.keys(this.errors).length > 0;
}
clearErrors() {
this.errors = {};
return this;
}
setError(key, message) {
if (typeof key === 'object') {
for (const newKey in key) {
this.setError(newKey, key[newKey][0]);
}
}
else {
this.errors = Object.assign({}, this.errors, { [key]: message });
}
return this;
}
request(method, url, data = {}, options) {
if (!Form.http) {
Form.setAxiosInstance(axios.create({}));
}
this.processing = true;
this.clearErrors();
Form.http.request({ method, url, ...data })
.then(({ data }) => {
if (options.onSuccess) {
options.onSuccess(data);
}
})
.catch((error) => {
if (error.response && error.response.status === 422) {
const validationErrors = error.response.data;
if (validationErrors && validationErrors.errors) {
this.setError(validationErrors.errors);
}
if (options.onValidationErrors) {
options.onValidationErrors(this.errors);
}
return;
}
if (options.onError) {
options.onError(error);
}
})
.finally(() => {
this.processing = false;
if (options.onFinish) {
options.onFinish();
}
});
}
post(route, options = {}) {
this.request('post', route, { data: this.fields }, options);
}
put(route, options = {}) {
this.request('put', route, { data: this.fields }, options);
}
patch(route, options = {}) {
this.request('patch', route, { data: this.fields }, options);
}
delete(route, options = {}) {
this.request('delete', route, {}, options);
}
reset() {
this._fields = Object.assign({}, this._initialData);
for (const key of Object.keys(this._fields)) {
this[key] = this._fields[key];
}
this.clearErrors();
return this;
}
}
Form.http = null;
function useForm(fields) {
return new Form(fields);
}
function setFormAxios(axios) {
Form.setAxiosInstance(axios);
}
exports.setFormAxios = setFormAxios;
exports.useForm = useForm;
//# sourceMappingURL=index.js.map