Alex
Alex13mo ago

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)
}
7 Replies
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Alex
AlexOP13mo ago
Can you please tell me what formData?.email means? does it check if its not undefined and contains a value?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Alex
AlexOP13mo ago
and what if formData is undefined will it say something like cannot read property of undefined?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Alex
AlexOP13mo ago
Oh thanks a lot this is amazing.
reactibot
reactibot13mo ago
This thread hasn’t had any activity in 36 hours, so it’s now locked. Threads are closed automatically after 36 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1190617882028167249

Did you find this page helpful?