Reputation: 155
I'm a little new to react and i can't understand why my object property is undefined but when i console.log my object is appearing okay see this screenshot:
This is my custom hook useForm:
const useForm = (callback, validateRegister) => {
const [values, setValues] = useState({
name: '',
email: '',
password: '',
confirmPass: '',
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (event) => {
const { name, value } = event.target;
setValues({
...values,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
setErrors(validateRegister(values)); // validateReister is another function that returns and object with these properties.
setIsSubmitting(true);
};
useEffect(() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
callback();
}
}, [errors]);
return {
handleChange,
handleSubmit,
values,
errors,
};
};
export default useForm;
Component:
const { handleChange, handleSubmit, values, errors } = useForm(
submit,
validateRegister
);
Problem:
{errors.nameError}
Is not showing up, is not appearing on console.log either. Any idea?
Upvotes: 0
Views: 358
Reputation: 8316
I think your validateRegister(values)
returns a Promise
. Try changing your implementation to the below :-
const handleSubmit = (event) => {
event.preventDefault();
validateRegister(values).then(data => setErrors(data)).catch(err => console.log(err));
setIsSubmitting(true);
};
Upvotes: 2
Reputation: 109
Replace setErrors(validateRegister(values));
with
validateRegister(values).then(data => setErrors(data)).catch(e => console.log(e));
Upvotes: 1