Home > Blockchain >  Firebase auth React dom router navigate if there is no error
Firebase auth React dom router navigate if there is no error

Time:05-16

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);
  };

CodePudding user response:

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

  • Related