I’m stuck in a problem related to react useState
and not sure how to solve it.
Some background. I’ve a register form with validation on blur on each field. The validation works if I blur individual field which is basically setting the error message (using useState
) if there’s any error. I’ve called the same validation methods on form submit. So that I don’t have to write a duplicate code.
The problem arise when I submit without invoking the blur methods. It runs all the methods and set the error messages but the useState
values are not available. I read some articles that says to use useEffect
but then it will either run without any watcher or with watchers. If it runs without any watcher then the ux will be bad and user will be shown errors when they freshly come to the page. Please see image
OR
If we add watchers in our useEffect
then validation will be run on each key stroke which I don’t want.
useEffect(()=>{
handleOnBlur("firstname", firstname);
handleOnBlur("lastname", lastname);
handleOnBlurPassword(password);
},[firstname, lastname, password])
I’m looking to solve this without useEffect
or some other way in which I don’t compromise the UX.
I’ve created a codesandbox. Please have a look if my i’m not clear in my description
4
Answers
I’m not very experienced with React but I think for this kind of forms it’s best practice to use React useRef hook instead of useState.
This way the state will not change with every type of the user.
You can use the useEffect with empty brackets for the mount (first render) and add another useEffect with names and password dependecies for later checks.
Hope this is helpful 🙂
You can add another validations step on the
onSubmit
event, or, if the form is submitted without this React event, then manually run validations just before submitting the data to the server, and obviously, if the form is deemed "invalid", do not continue (do not save the form on the server)Put your complete form validation step here, instead of those 3 marked lines:
Create a function that validates all the fields and returns
true
if everything is valid, and only then proceed with the actual form submission.You may use useRef() instead of useState using following syntax :
const firstName = useRef() and obtain firstname’s values as firstname.current.value.
Following link might help you : w3schools.com/react/react_useref.asp
According to the defined requirement i have updated the code.
Please look into it and update the changes as well.
This code might be helpful to you.
thank you so much !
App.js