Alberto Ornelas
Alberto Ornelas

Reputation: 31

Why I need to press twice times to submit my form?

I want to submit my login form, but I need to press twice times to accomplish login form, I don't know what happen. I'm using styled components, this Button Form is an input tag Also I'm using firebase-hooks I just want to click one time and submit

Here my code

export default function LoginForm() {
  // submit
  const handleLogin = (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(email, password);

    if (user) {
      setTimeout(() => {
        history.push(`${ROUTES.HOME}`);
      }, 1000);
    }
  };

  if (loading) {
    return <Loading />;
  }

  return (
    <FormContainer onSubmit={(e) => handleLogin(e)}>
      <LogoContainer>
        <img
          src="https://firebasestorage.googleapis.com/v0/b/auth-c068d.appspot.com/o/instagram%2Finstagram-signup.png?alt=media&token=cdafffb1-3034-474d-be96-d507b5e416c6"
          alt="instagram-logo"
        />
      </LogoContainer>

      <input
        id="email"
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
        required
      />
      <input
        id="password"
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
        required
      />
      <ButtonForm type="submit" name="btn-login" value="Log In" />
      <p>
        Don't have an account? <Link to="/signup">Sign Up</Link>
      </p>
      {error && <Error errorMessage={error.message} />}
    </FormContainer>
  );
}

Upvotes: 1

Views: 559

Answers (2)

Chris Warren
Chris Warren

Reputation: 88

It looks like you will need to use a useEffect hook here. Your handleLogin function only runs once on each click. The first time you submit, user is undefined as expected. It works when you click it the second time because user is truthy.

Try removing this from the handleLogin function.

if (user) {
  setTimeout(() => {
    history.push(`${ROUTES.HOME}`);
  }, 1000);
}

Then add a useEffect hook.

useEffect(() => {     
if (user) {
  setTimeout(() => {
    history.push(`${ROUTES.HOME}`);
  }, 1000);
}}, [user])

This effect will run on component mount, and after each time your user state is changed. (This is assuming your using react state for user, as I can't see where user is coming from)

Upvotes: 4

ibra
ibra

Reputation: 433

change the type of button from type="submit" to type="button" and handle click using onCkick={() => clickHandler()}

Upvotes: 0

Related Questions