Search code examples
reactjsfirebasefirebase-authenticationtry-catch

React/firebase: show error message in jsx


I would be happy to get any help. I would like to show authentication message in jsx but so far I am only able to throw alerts. I wanted to implement useState() with catch block inside handleSignUp a some reason handleSignUp never manages to catch errors. Here is the current state of my functions.

const [validation, setValidation] = useState("");

async function signUp(name, email, password) {
    createUserWithEmailAndPassword(auth, email, password)
      //add user to database
      .then(async (userCredential) => {
   
        const user = userCredential.user; 
        const docRef = doc(allUsers, user.uid);
        await setDoc(docRef, { name: name, email: email });
      })
      .catch((error) => {
      
        if (error.code == "auth/email-already-in-use") {
          alert("The email address is already in use");
      
        } else if (error.code == "auth/invalid-email") {
            alert("The email address is not valid.");
           
        } else if (error.code == "auth/operation-not-allowed") {
            alert("Operation not allowed.");
        } else if (error.code == "auth/weak-password") {
            alert("The password is too weak.");
        }
  
      } );

  }

 const handleSignUp = async (e) =>{ 
    e.preventDefault()
    if((pwdRef.current.value.length|| pwdConfirmRef.current.value.length)<6){
      setValidation("Le mot de passe doit contenir 6 caractères minimum ")
      return
    }
     if(pwdRef.current.value !== pwdConfirmRef.current.value){
      setValidation("Les mots de passe saisis ne correspondent pas")
      return
    }  
      await signUp(nameRef.current.value, emailRef.current.value, pwdRef.current.value);
      formRef.current.reset();
  
  }

 //JSX
<form ref={formRef} onSubmit = {handleSignUp}>
      .........
     <p className="validation">{validation}</p>
  
  </form>

Solution

  • You can try below code, It has shifted from createUserWithEmailAndPassword.then to await createUserWithEmailAndPassword and a try catch block, give it a try.

        const [validation, setValidation] = useState("");
        
        async function signUp(name, email, password) {
    try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
     const user = userCredential.user; 
                const docRef = doc(allUsers, user.uid);
                await setDoc(docRef, { name: name, email: email });
              //add user to database
    
    } catch(error) {
       if (error.code == "auth/email-already-in-use") {
                  setValidation("The email address is already in use");
                  // alert();
              
                } else if (error.code == "auth/invalid-email") {
                  setValidation("The email address is not valid.");
                   
                } else if (error.code == "auth/operation-not-allowed") {
                  setValidation("Operation not allowed.");
                } else if (error.code == "auth/weak-password") {
                  setValidation("The password is too weak.");
                }
    }
            
        
          }
        
         const handleSignUp = async (e) =>{ 
            e.preventDefault()
            setValidation("");
            if((pwdRef.current.value.length|| pwdConfirmRef.current.value.length)<6){
              setValidation("Le mot de passe doit contenir 6 caractères minimum ")
              return
            }
             if(pwdRef.current.value !== pwdConfirmRef.current.value){
              setValidation("Les mots de passe saisis ne correspondent pas")
              return
            }  
              await signUp(nameRef.current.value, emailRef.current.value, pwdRef.current.value);
              formRef.current.reset();
          
          }
        
         //JSX
        <form ref={formRef} onSubmit = {handleSignUp}>
              .........
             <p className="validation">{validation}</p>
          
          </form>