Skip to content

Commit

Permalink
add new function setValidatorSchema to be able to set a new validatio…
Browse files Browse the repository at this point in the history
…n state #7
  • Loading branch information
llauderesv committed May 5, 2020
1 parent 7c1e6a8 commit feb896d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
4 changes: 0 additions & 4 deletions src/example/Form/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ function Form() {
tags: { value: '', error: '' },
};

const delay = () => new Promise((resolve) => setTimeout(resolve, 3000));

// Create your own validationStateSchema
// stateSchema property should be the same in validationStateSchema
// in-order a validation to works in your input.
Expand Down Expand Up @@ -49,8 +47,6 @@ function Form() {
dirty,
handleOnChange,
handleOnSubmit,
setFieldError,
setFieldValue,
setStateSchema,
disable,
} = useForm(stateSchema, stateValidatorSchema, onSubmitForm);
Expand Down
15 changes: 13 additions & 2 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ function useForm(
submitFormCallback
) {
const [state, setStateSchema] = useState(stateSchema);
const [validatorSchema, setValidatorSchema] = useState(stateValidatorSchema);

const [values, setValues] = useState(get_prop_values(state, VALUE));
const [errors, setErrors] = useState(get_prop_values(state, ERROR));
Expand Down Expand Up @@ -45,6 +46,15 @@ function useForm(
setErrors(errors);
}, [state]); // eslint-disable-line

useEffect(() => {
const errors = Object.keys(values).reduce((accu, curr) => {
accu[curr] = validateField(curr, values[curr]);
return accu;
}, {});

setErrors(errors);
}, [validatorSchema]); // eslint-disable-line

// For every changed in our state this will be fired
// To be able to disable the button
useEffect(() => {
Expand All @@ -67,7 +77,7 @@ function useForm(
// Function used to validate form fields
const validateField = useCallback(
(name, value) => {
const fieldValidator = stateValidatorSchema[name];
const fieldValidator = validatorSchema[name];
// Making sure that stateValidatorSchema name is same in
// stateSchema
if (!fieldValidator) {
Expand All @@ -93,7 +103,7 @@ function useForm(

return error;
},
[stateValidatorSchema, values]
[validatorSchema, values]
);

// Set Initial Error State
Expand Down Expand Up @@ -148,6 +158,7 @@ function useForm(
errors,
disable,
setStateSchema,
setValidatorSchema,
setFieldValue,
setFieldError,
handleOnChange,
Expand Down

0 comments on commit feb896d

Please sign in to comment.