Handling undefined text input value

I have this condition here that checks if the value is undefined

console.log("Value: " + typeof getValues('departmentId'))
if (String(getValues('departmentId')) != "" ||
    String(getValues('departmentDesc')) != "" ||
    typeof getValues('departmentId') !== undefined ||
    typeof getValues('departmentDesc') !== undefined){
    dispatch(setIsConfirm(true))
    console.log("Clearing fields || Value: " + getValues('departmentId'))
}

But for some reason it still ran even though it is undefined, here is the picture of the
console

>Solution :

typeof returns a string. So you need to do this instead:

console.log("Value: " + typeof getValues('departmentId'))
if (typeof getValues('departmentId') !== "undefined" || typeof getValues('departmentDesc') !== 'undefined'){
    dispatch(setIsConfirm(true))
    console.log("Clearing fields || Value: " + getValues('departmentId'))
}

Also, make sure you really need OR || operator and not AND &&. Replace it if needed.

Leave a Reply