简体   繁体   中英

Firebase auth React dom router navigate if there is no error

I have a sign up function that will register a user in firebase auth. My issue is that the users gets navigated to the home page even if there is a error with sign up. How can I fix my function to programmatically navigate users if there is no error durning sign up

 const handleSubmit = (event) => {
    event.preventDefault();

    const data = new FormData(event.currentTarget);

    try {
      //signup is a prop function
      signup(data.get("email"), data.get("password"));
    } catch (error) {
      setError(error.message);
      return;
    }

    navigate("/" + location.search);
  };

Without additional context, I'm taking a confident guess that its most likely because your signup is an async function. Without await on signup , the signup will start only after handleSubmit finishes. In order to await on it, you have to declare handleSubmit to be an async arrow function.

Pay attention to the async and await I've added.

const handleSubmit = async (event) => {
  event.preventDefault();

  const data = new FormData(event.currentTarget);

  try {
    await signup(data.get("email"), data.get("password"));
  } catch (error) {
    setError(error.message);
    return;
  }

  navigate("/" + location.search);
};

To better understand this concept, make sure you read more about Async Functions and the JS Event Loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM