Phelizer
Phelizer

Reputation: 319

React-router history.push does not actually redirect

I want my app to redirect a user on form submit. I have AuthPage conponent:

const AuthPage = () => {
  const history = useHistory();

  const test = () => {
    history.push("/boards");
  };

  const submitHandler = () => {
    fetch(...)
      .then((res) => res.json())
      .then((result) => {
        history.push("/boards");
      });
  };

  return (
    <div className="AuthPage">
      <form onSubmit={submitHandler}>
        // my form here
        <input type="submit" value="Sign in" />
      </form>
    </div>
  );
};

When I set onSubmit={test} - everything works fine, redirect works. But when I set onSubmit={submitHandler} instead - history object gets updated, but the redirect actually doesn't happen. I noticed that for a milisecond my client url changes from where I was (/) to /boards, but than instantly gets back, so I actually stay on the same page. Any ideas on why can that happen?

Upvotes: 0

Views: 124

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53984

Try preventing the default refresh of a submitted form:

const submitHandler = (e) => {
  e.preventDefault();
  ...
};

Upvotes: 2

Related Questions