vcc-ui
Version:
A React library for building user interfaces at Volvo Cars
76 lines (74 loc) • 1.81 kB
JavaScript
import { arrayReduce } from 'fast-loops';
export function useForm() {
for (var _len = arguments.length, fields = new Array(_len), _key = 0; _key < _len; _key++) {
fields[_key] = arguments[_key];
}
function touchFields() {
fields.forEach(field => field.touch());
}
function reset() {
fields.forEach(field => field.update(field.initial));
}
function submit(onSubmit) {
const isValid = arrayReduce(fields, (isValid, field) => isValid && field.isValid, true);
const data = arrayReduce(fields, (data, _ref) => {
let {
value,
name
} = _ref;
data[name] = value;
return data;
}, {});
// if the form is invalid, we touch all fields to reveal the error messages
if (!isValid) {
touchFields();
}
onSubmit(isValid, data);
}
return {
touchFields,
submit,
reset
};
}
// TODO: make this only available in development
// for now we're fine due to code splitting though
export function useFormDebugger() {
for (var _len2 = arguments.length, fields = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fields[_key2] = arguments[_key2];
}
const isValid = arrayReduce(fields, (isValid, field) => isValid && field.isValid, true);
const data = arrayReduce(fields, (data, _ref2) => {
let {
name,
value
} = _ref2;
data[name] = value;
return data;
}, {});
const fieldData = arrayReduce(fields, (data, _ref3) => {
let {
name,
value,
isValid,
isTouched,
isDisabled,
isLoading,
errorMessage
} = _ref3;
data[name] = {
value,
isTouched,
isValid,
isDisabled,
isLoading,
errorMessage
};
return data;
}, {});
return {
data,
fields: fieldData,
isValid
};
}