Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda