AlexA
Reactiflux3y ago
9 replies
Alex

alexnoah.dev – 11-30 Dec 30

How can I make this code shorter,
if(formData && formData.email && formData.password && formData.email.length && formData.password.length)

First I check if the variable (useState) exist, then I check if it is object and contains email key and password key, then I check if the email and password key has any value.

One way that come in my mind is to have the variable like this by default :
const formData = {email: '', password: ''}

So then I can remove this part of my code :
if(formData && formData.email && formData.password)

But I don't want to do that and I'm looking for another way around, is there any? (Why don't I want to do this? because if I want to clear the form I will use
setFormData({})
and I don't want to use
setFormData({email: '', password: ''})
, again why don't I want to do this? what if I change my mind about having only email and password then for clearing form and default value of formData I should make an edit which is not nice), So if is there any way around let me know please, if not I guess I should have a default value in different variable and do something like this :
const defaultFormData = {email: '', password: ''}
const [formData, setFormData] = useState(defaultFormData)
function clearForm () {
  setFormData(defaultFormData)
}
Was this page helpful?