首页 > 解决方案 > React Native 中的注册问题(关于并发)

问题描述

嘿,我正在做一个注册表单,每次更改用户名文本输入时,我都会查看我的数据库是否可用(将文本输入的图标颜色更改为红色或绿色)。

  const checkUsername = async () => {
    // Get username from input
    const username = usernameInput.current.props.value;

    let isUsernameAvailable = false;

    if (!isEmpty(username)) {
      const { firebase } = props;
      // Check if the username is available on the database and valid
      isUsernameAvailable =
        (await firebase.checkUsername(username)) && validateUsername(username);
    }

    setIsUsernameAvailable(isUsernameAvailable);
  };

我有自己的 firebase 规则,仅在不存在时创建用户名,但有时,当我快速输入输入并单击提交按钮时,会创建一个用户名不可用的用户。

这是提交功能:

const signUp = async () => {
    // Do not try to sign up again if the user is currently signing up
    if (isLoading) return;

    const { firebase, toast } = props;

    const username = usernameInput.current.props.value;
    const email = emailInput.current.props.value;
    const password = passwordInput.current.props.value;
    const repeatPassword = repeatPasswordInput.current.props.value;

    // It is too important to check that the username is not taken
    await checkUsername(username);

    const formError = validateForm(username, email, password, repeatPassword);

    // Do not sign up if the form is incorrect
    if (formError) {
      // Show error message
      toast.current.show(formError, 3500);
      return;
    }

    // Start loading
    setIsLoading(true);

    // Try to create the user with the email and password
    firebase
      .createUserWithEmailAndPassword(email, password)
      .then((currentUser) => {
        // Get the username from the input
        const username = usernameInput.current.props.value;

        // Create a user with this username and the current user uid in the db
        firebase.createUserWithUsername(username, currentUser.user.uid);
      })
      .catch((err) => {
        if (err.code !== "auth/too-many-request") {
          // Convert error code to message
          const message = firebase.parseError(err.code);

          // Show error message
          toast.current.show(message, 3500);

          // Finish loading
          setIsLoading(false);
        }
      });

    /* 
      Pd: It has no sense to make a query if the username, email and password 
      are not valid. We avoid making extra queries.
    */
  };

有任何想法吗?

标签: javascriptfirebasereact-nativegoogle-cloud-firestoreexpo

解决方案


推荐阅读