Home > Mobile >  How do I handle if the api error message is undefined?
How do I handle if the api error message is undefined?

Time:11-25

If the login is successful, I do not receive an error message. My problem is that if no error message is received, the value of data.error.message is undefined and the program crashes. How can I solve this?

 if(data.error.message === 'EMAIL_NOT_FOUND'){
      setError({
        title: "EMAIL_NOT_FOUND",
        message: "This email address is not registered.",
      });
      setIsLoading(false);
      return;
    }
    if(data.error.message === 'EMAIL_NOT_FOUND' && data.error.message !== undefined){
      setError({
        title: "EMAIL_NOT_FOUND",
        message: "This email address is not registered.",
      });
      setIsLoading(false);
      return;
    }

I tried this too but same error.

CodePudding user response:

Probably you getting error because you are trying to read from object that is undefined.

You can make modify your condition to handle case when error is undefined:

 if(data?.error?.message && data.error.message === 'EMAIL_NOT_FOUND'){
   ...
 }

That way you will make sure that error and message exist and not undefined.

  • Related