无法阻止导航到下一页反应firebase

发布于 2025-01-17 12:34:30 字数 1320 浏览 0 评论 0原文

我正在使用Firebase创建一个Web应用程序,并进行反应。我的注册功能有效,但是我在边缘案例中遇到了一些麻烦,例如用户尝试使用已经存在的电子邮件注册时。如何防止导航到下一页?

async function handleSignup(e) {
        e.preventDefault()
        validatePassword()
        try {
            // setError('')
            setLoading(true)
            await signup(emailRef.current.value, passwordRef.current.value)
            history.push('/profile')
            console.log('created User' + currentUser.uid)
        } catch {
            setError('Failed to Create an Account')
        }
        setLoading(false)
    }
function signup(email, password) {
        auth.createUserWithEmailAndPassword(email, password)
            .then((cred) => {
                return db.collection('students').doc(cred.user.uid).set()
            })
            .catch((e) => {
                if (e.code === 'auth/email-already-in-use') {
                    console.log('Email already in Use')
                    alert('Email already in use')
                }
                if (e.code === 'auth/weak-password')
                    alert(
                        'Password must be at least 7 characters long and contain special characters'
                    )
            })
    }

I am creating a web app using firebase and react. My signup function works but I am having some trouble with edge cases such as when a user tries to signup with an email that already exists. How do I prevent navigation to the next page?

async function handleSignup(e) {
        e.preventDefault()
        validatePassword()
        try {
            // setError('')
            setLoading(true)
            await signup(emailRef.current.value, passwordRef.current.value)
            history.push('/profile')
            console.log('created User' + currentUser.uid)
        } catch {
            setError('Failed to Create an Account')
        }
        setLoading(false)
    }
function signup(email, password) {
        auth.createUserWithEmailAndPassword(email, password)
            .then((cred) => {
                return db.collection('students').doc(cred.user.uid).set()
            })
            .catch((e) => {
                if (e.code === 'auth/email-already-in-use') {
                    console.log('Email already in Use')
                    alert('Email already in use')
                }
                if (e.code === 'auth/weak-password')
                    alert(
                        'Password must be at least 7 characters long and contain special characters'
                    )
            })
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

残花月 2025-01-24 12:34:30

您需要使用 Promise

const signup = (email, password) => new Promise((resolve, reject) => {
  auth.createUserWithEmailAndPassword(email, password)
      .then((cred) => {
          return resolve(db.collection('students').doc(cred.user.uid).set())
      })
      .catch((e) => {
          if (e.code === 'auth/email-already-in-use') {
              console.log('Email already in Use')
              return reject('Email already in use')
          }
          if (e.code === 'auth/weak-password')
              return reject('Password must be at least 7 characters long and contain special characters')
      })
});

// and you can use now the try ... catch

try {
  // setError('')
  setLoading(true)
  await signup(emailRef.current.value, passwordRef.current.value)
  history.push('/profile')
  console.log('created User' + currentUser.uid)
} catch(error) {
  setError(error)
}

You need to refactor your async singup using Promise.

const signup = (email, password) => new Promise((resolve, reject) => {
  auth.createUserWithEmailAndPassword(email, password)
      .then((cred) => {
          return resolve(db.collection('students').doc(cred.user.uid).set())
      })
      .catch((e) => {
          if (e.code === 'auth/email-already-in-use') {
              console.log('Email already in Use')
              return reject('Email already in use')
          }
          if (e.code === 'auth/weak-password')
              return reject('Password must be at least 7 characters long and contain special characters')
      })
});

// and you can use now the try ... catch

try {
  // setError('')
  setLoading(true)
  await signup(emailRef.current.value, passwordRef.current.value)
  history.push('/profile')
  console.log('created User' + currentUser.uid)
} catch(error) {
  setError(error)
}

恍梦境° 2025-01-24 12:34:30

已经存在的电子邮件不是边缘案例:)

history.push('/profile')仅在注册为成功时才调用,
因此,如果注册失败,则应丢失错误并转到捕获块。
可能值得检查注册功能是否会如您期望的

An already existing email is not an edge case :)

history.push('/profile') should only be invoked if sign-up is succesfull,
so if signup fails it should throw an error and go to the catch block.
might be worth to check if signup function throws an error as you expect

感性 2025-01-24 12:34:30

一种方法是,当您在 signup 函数中遇到错误时,您应该抛出该错误,以便 handleSignup 不会执行 await 之后的代码注册(...)

基本上,您的目标是在出现错误时突破“成功障碍”。 alert() 不会提供预期的行为,因为它不会抛出任何内容,这就是即使您的 signup 也会触发 history.push 的原因被拒绝并出现警报。

相反,它会捕获错误并执行 setError(...)

因此,您的 signup 函数将如下所示,

function signup(email, password) {
  auth.createUserWithEmailAndPassword(email, password)
    .then((cred) => {
      return db.collection('students').doc(cred.user.uid).set()
    })
    .catch((e) => {
      if (e.code === 'auth/email-already-in-use') {
        throw new Error(`Email is already in use, ${e}`)
      }
      if (e.code === 'auth/weak-password')
        throw new Error('Password must be at least 7 characters long and contain special characters')
      }
    )}

One way of doing so is when you get an error in the signup function, you should throw the error so handleSignup won't execute the code that comes after await signup(...).

Basically, your goal is to break out of the "success block" in case there's an error. alert() will not provide the expected behavior simply because it will not throw anything and that is the reason history.push triggers even though your signup rejected and the alert showed up.

Instead, it will catch the error and execute setError(...).

Therefore, your signup function would look something like this,

function signup(email, password) {
  auth.createUserWithEmailAndPassword(email, password)
    .then((cred) => {
      return db.collection('students').doc(cred.user.uid).set()
    })
    .catch((e) => {
      if (e.code === 'auth/email-already-in-use') {
        throw new Error(`Email is already in use, ${e}`)
      }
      if (e.code === 'auth/weak-password')
        throw new Error('Password must be at least 7 characters long and contain special characters')
      }
    )}
作妖 2025-01-24 12:34:30

Firebase 不允许您使用同一电子邮件注册两次。我建议使用他们的错误消息。
他们也不允许输入六个字符以下的密码。

您是否正在寻找适合其他系统的特定解决方案或通用解决方案?

您可以尝试我的存储库。我使用(免费)Firebase Auth 服务以及它们发回的错误。

Firebase is not allowing you to signup up twice with the same email. I recommend using their error messages.
They also do not allow entering a password under six characters.

Are you looking for a specific solution or a general solution that will fit other systems?.

You can try my repository. I worked with the (free) Firebase Auth service and the errors they send back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文