Home > Mobile >  Handling undefined text input value
Handling undefined text input value

Time:06-14

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

CodePudding user response:

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.

CodePudding user response:

I went with this:

  if ((String(getValues('departmentId')) !== "" && typeof getValues('departmentId') !== "undefined") ||
            (String(getValues('departmentDesc')) !== "" && typeof getValues('departmentDesc') !== "undefined")){
            dispatch(setIsConfirm(true))
        }
  • Related