diff --git a/src/Form/index.js b/src/Form/index.js index 20615a0..c571109 100644 --- a/src/Form/index.js +++ b/src/Form/index.js @@ -10,7 +10,7 @@ function Form() { tags: { value: '', error: '' }, }; - const delay = () => new Promise(resolve => setTimeout(resolve, 5000)); + const delay = () => new Promise(resolve => setTimeout(resolve, 3000)); // Create your own validationStateSchema // stateSchema property should be the same in validationStateSchema @@ -58,8 +58,8 @@ function Form() { useEffect(() => { delay().then(() => { setStateSchema({ - first_name: { value: 'Denise', error: '' }, - last_name: { value: '', error: '' }, + first_name: { value: 'Ellie', error: '' }, + last_name: { value: 'Eilish', error: '' }, tags: { value: '', error: '' }, }); // setFieldValue({ name: 'first_name', value: 'Hello' }); @@ -81,7 +81,9 @@ function Form() { onChange={handleOnChange} /> - {errors.first_name &&

{errors.first_name}

} + {errors.first_name && dirty.first_name && ( +

{errors.first_name}

+ )}
diff --git a/src/useForm.js b/src/useForm.js index 9916971..ab0e5ab 100644 --- a/src/useForm.js +++ b/src/useForm.js @@ -17,7 +17,7 @@ function useForm( const [values, setValues] = useState(get_prop_values(state, VALUE)); const [errors, setErrors] = useState(get_prop_values(state, ERROR)); - const [dirty, setDirty] = useState(get_prop_values(state)); + const [dirty, setDirty] = useState(get_prop_values(state, false)); const [disable, setDisable] = useState(true); const [isDirty, setIsDirty] = useState(false); @@ -29,12 +29,18 @@ function useForm( setInitialErrorState(); }, []); // eslint-disable-line - // If state schema changes update all fields + // Set a brand new field values and errors + // If stateSchema changes useEffect(() => { - setValues(get_prop_values(state, VALUE)); - setErrors(get_prop_values(state, ERROR)); - setDirty(get_prop_values(state, true)); - }, [state]); + const values = get_prop_values(state, VALUE); + setValues(values); + setErrors( + Object.keys(values).reduce((accu, curr) => { + accu[curr] = validateField(curr, values[curr]); + return accu; + }, {}) + ); + }, [state]); // eslint-disable-line // For every changed in our state this will be fired // To be able to disable the button diff --git a/src/utils.js b/src/utils.js index 089fd58..d16f661 100644 --- a/src/utils.js +++ b/src/utils.js @@ -2,6 +2,10 @@ export const VALUE = 'value'; export const ERROR = 'error'; export const REQUIRED_FIELD_ERROR = 'This is required field'; +function is_bool(value) { + return typeof value === 'boolean'; +} + /** * Determines a value if it's an object * @@ -23,7 +27,7 @@ export function is_required(value, isRequired) { export function get_prop_values(stateSchema, prop) { return Object.keys(stateSchema).reduce((field, key) => { - field[key] = !prop ? false : stateSchema[key][prop]; + field[key] = is_bool(prop) ? prop : stateSchema[key][prop]; return field; }, {});