Why do I have to check if function is null inside an if?

Hello everyone, sorry for the very generic question, but I can't seem to find an answer and I'm a bit confused, let's see with an example:

{props.showForm && (
<DropdownMenuItem onClick={() => props.showForm()}>
<span>Log result</span>
</DropdownMenuItem>
)}

{props.showForm && (
<DropdownMenuItem onClick={() => props.showForm()}>
<span>Log result</span>
</DropdownMenuItem>
)}
Does anyone know why this has an error Cannot invoke an object which is possibly 'undefined' even though I've made the check inside the if? Thanks in advance!
Solution:
It’s because you’re making an arrow function that relies on accessing props.showForm() off of the object From the time props.showForm is check and called it could become undefined because it exists on an object, to try this out below that line set props.showForm to undefined and see what happens To fix it, assign showForm to a constant variable and check the variable instead, then call the variable...
Jump to solution
3 Replies
whatplan
whatplan13mo ago
this is impossible to answer without more code what if statement?
Solution
Rhys
Rhys13mo ago
It’s because you’re making an arrow function that relies on accessing props.showForm() off of the object From the time props.showForm is check and called it could become undefined because it exists on an object, to try this out below that line set props.showForm to undefined and see what happens To fix it, assign showForm to a constant variable and check the variable instead, then call the variable const showForm = props.showForm …
Mr.T 🐻⛓
Mr.T 🐻⛓13mo ago
Smart! Thanks for your help!
Want results from more Discord servers?
Add your server