Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
async/await + try/catch not working as spected when using a .then() function

I'm working on a project using react, and i need to redirect to a logged in page if register is successful, so I added a state called redirect, empty when you access the register form that I need to set so the page can redirect, since I use a handler, this is the relevant component code:

    class Registro extends Component {
        constructor() {
            super();
            this.state = {
                email: "",
                password: "",
                passwordConfirm: "",
                userName: "",
                redirect: "",
            };
        }
    handleRedirect = () => {
        this.setState({ redirect: "/aplicacion" });
        console.log(this.state);
    }
  render() {
        if (this.state.redirect) {
            return <Navigate to={this.state.redirect} />
          }
        
        return (
          <button id="submit" className="btn btn-outline-accesible col-3 m-2 mt-3" 
                 onClick={() => {
                 registerWithEmailAndPassword(this.state.userName, this.state.email, this.state.password).then(
                      handleRedirect() 
                 )}}>Acceder</button>

And the register with email and password is this function:

    const registerWithEmailAndPassword = async (name, email, password) => {
    try {
        console.log(name, email, password)
      const res = await createUserWithEmailAndPassword(auth, email, password);
      const user = res.user;
      await setDoc(doc(db, "users", email), {
        email: email,
        nombre: name,
        pass: password
      });
      alert("Registro completado con éxito")
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

The expected outcome is that if the register is successful, the page reloads and you can go on your merry way, but if there's an error, the page won't load and the error will be alerted to the user. What is happening is that in the case there's an error, the page redirects you and then shows you an alert with the error data.

Thanks for reading and pondering this with me.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

What is the idea beneath mixing approach?

This should work

class Registro extends Component {
  render() {
    if (this.state.redirect) {
      return <Navigate to={this.state.redirect} />;
    }

    return (
      <button
        id="submit"
        className="btn btn-outline-accesible col-3 m-2 mt-3"
        onClick={this.handleClick}
      >
        Acceder
      </button>
    );
  }

  handleClick = async () => {
    try {
      await registerWithEmailAndPassword(
        this.state.userName,
        this.state.email,
        this.state.password
      );
      handleRedirect();
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };
}

const registerWithEmailAndPassword = async (name, email, password) => {
  console.log(name, email, password);
  const res = await createUserWithEmailAndPassword(auth, email, password);
  const user = res.user;
  await setDoc(doc(db, "users", email), {
    email: email,
    nombre: name,
    pass: password,
  });
  alert("Registro completado con éxito");
};

UPDATE: Please note that registerWithEmailAndPassword also updated to support correct error handling according to the request

about 4 years ago · Juan Pablo Isaza Report

0

Your registerWithEmailAndPassword function is async, so it returns a Promise. In this function, you call another async function, and you wait for its response. You are catching the exceptions thrown by setDoc. So your registerWithEmailAndPassword always resolves. What you can do is :

  • Return something if the function succeeds
  • Return a rejected Promise in case of error
const registerWithEmailAndPassword = async (name, email, password) => {
    try {
        console.log(name, email, password)
      const res = await createUserWithEmailAndPassword(auth, email, password);
      const user = res.user;
      await setDoc(doc(db, "users", email), {
        email: email,
        nombre: name,
        pass: password
      });
      alert("Registro completado con éxito")
      return true
    } catch (err) {
      console.error(err);
      alert(err.message);
      return Promise.reject(false);
    }
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!