Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda