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)
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: ''}
const formData = {email: '', password: ''}
So then I can remove this part of my code :
if(formData && formData.email && formData.password)
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)
}
const defaultFormData = {email: '', password: ''}
const [formData, setFormData] = useState(defaultFormData)
function clearForm () {
setFormData(defaultFormData)
}
UU
Unknown User110d ago
A
Alex110d ago
Can you please tell me what formData?.email means? does it check if its not undefined and contains a value?
UU
Unknown User110d ago
A
Alex110d ago
and what if formData is undefined will it say something like cannot read property of undefined?
UU
Unknown User110d ago
A
Alex110d ago
Oh thanks a lot this is amazing.
UU
Unknown User109d ago