@modern-kit/react
Version:
38 lines (35 loc) • 1.13 kB
JavaScript
import { useState, useCallback } from 'react';
import { usePreservedCallback } from '../usePreservedCallback/index.mjs';
import { noop } from '@modern-kit/utils';
function useInputState(initialValue = "", options = {}) {
const { validate } = options;
const [value, setValue] = useState(initialValue);
const [error, setError] = useState(null);
const preservedValidate = usePreservedCallback(validate ?? noop);
const onChange = useCallback(
(e) => {
const { value: value2 } = e.target;
const validationError = preservedValidate(value2);
if (validationError) {
setError(validationError);
} else {
setError(null);
}
setValue(value2);
},
[preservedValidate]
);
const resetError = useCallback(() => {
setError(null);
}, []);
const resetValue = useCallback(() => {
setValue(initialValue);
}, [initialValue]);
const reset = useCallback(() => {
resetValue();
resetError();
}, [resetValue, resetError]);
return { value, error, onChange, resetError, resetValue, reset };
}
export { useInputState };
//# sourceMappingURL=index.mjs.map