title: ReactJS: Redirecting to a new page within an axios request
body: <p>I am building a MERN app with a login/register system and I am stuck on being able to redirect a user to a confirmation page which then prompts them to login.</p>
  
  <p>It seems like I could use the <code>useHistory</code> hook in react-router-dom and do <code>history.push()</code> within my axios request which is within my register function:</p>
  
  <pre><code>function handleRegister(e) {
  let history = useHistory();
  e.preventDefault();
  
  // Grab state
  const user = {
    username: formState.username,
    email: formState.email,
    password: formState.password,
    password2: formState.password2,
  };
  
  // Post request to backend
  axios
    .post("http://localhost:4000/register", user)
    .then((res) =&gt; {
     // Redirect user to the /thankyouForRegistering page which prompts them to login.
        history.push("/thankyouForRegistering");
  
    })
    .catch((err) =&gt; {
      console.log(err);
    });
  </code></pre>
  
  <p>}</p>
  
  <p>But this does not work. I get an error back saying:</p>
  
  <pre><code>React Hook "useHistory" is called in function "handleRegister" which is neither a React function component or a custom React Hook function 
  </code></pre>
  
  <p>Upon further research, it seems that in order to use the useHistory hook, it has to be within <code>&lt;Router&gt;</code>(possibly?) or directly on an onClick handler.</p>
  
  <p>So something like this:</p>
  
  <pre><code>&lt;Button onClick={() =&gt; history.push()}&gt;&lt;/button&gt;
  </code></pre>
  
  <p>I can't really do that though, because I am not using onClick for my register button, I am using onSubmit and my own register function.</p>
  
  <p>I also looked into using <code>&lt;Redirect /&gt;</code>, so I tried making a new state called <code>authorized</code>, set the authorize state to true in my axios request, and then tried this:</p>
  
  <pre><code>&lt;Route
              path="/thankyouForRegistering"
              render={() =&gt; (
                authorized ? (
                  &lt;ThankyouForRegistering /&gt;
                ) : (
                  &lt;Redirect to="/register" /&gt;
                ))
              }
            /&gt;
  </code></pre>
  
  <p>But this is not working either, and it also does not give me any kind of error.</p>
  
  <p>Does anyone know the best way to redirect a user to a new page upon registering/logging in? I've been struggling with this for going on two weeks.</p>
  
  <p>Thanks!!</p>
  
  <p>EDIT: Here is the entire component - it's a bit messy but if anyone needs any explanations please let me know.</p>
  
  <pre><code>import React, { useState } from "react";
  import {
    BrowserRouter as Router,
    Switch,
    Route,
    Redirect,
    useHistory,
  } from "react-router-dom";
  
  
  let navMenu;
  
  
  function App() {
   let history = useHistory();
    const [navMenuOpen, setNavMenuOpen] = useState(false);
    const [loggedIn, setLoggedIn] = useState(false);
    const [errorMsg, setErrorMsg] = useState("");
    const [token, setToken] = useState("");
    const [authorized, setAuthorized] = useState(false);
    const initialState = {
      username: "",
      email: "",
      password: "",
      password2: "",
    };
    const [formState, setFormState] = useState(initialState);
    const { username, email, password, password2 } = formState;
  
    const handleChange = (e) =&gt; {
      setFormState({ ...formState, [e.target.name]: e.target.value });
    };
  
    function handleRegister(e) {
      //const history = useHistory();
      e.preventDefault();
      // Grab setState
      const user = {
        username: formState.username,
        email: formState.email,
        password: formState.password,
        password2: formState.password2,
      };
  
      // Post request to backend
      axios
        .post("http://localhost:4000/register", user)
        .then((res) =&gt; {
          console.log(user);
          history.push("/thankyouForRegistering");
          setAuthorized(true);
          // Redirect user to the /thankyouForRegistering page which prompts them to login.
  
        })
        .catch((err) =&gt; {
          console.log(err);
        });
  
      // Once a user has registered, clear the registration form and redirect the user to a page that says thank you for registering, please login.
    }
  
    const handleLogin = (e) =&gt; {
      e.preventDefault();
      // Grab setState
      const userData = {
        email: formState.email,
        password: formState.password,
      };
  
      axios
        .post("http://localhost:4000/login", userData)
        .then((res) =&gt; {
          // Get token from local storage if there is a token
          localStorage.setItem("token", res.data.token);
          // If there is a token, redirect user to their profile and give them access to
          // their recipeList and shoppingList
          setLoggedIn(true);
          //props.history.push("/profile");
        })
        .catch((err) =&gt; console.log(err));
    };
  
    const navMenuToggle = () =&gt; {
      console.log("toggle");
      setNavMenuOpen(!navMenuOpen);
    };
  
    const navMenuClose = () =&gt; {
      setNavMenuOpen(false);
    };
  
    const logoutFromNavMenu = () =&gt; {
      setLoggedIn(false);
      navMenuClose();
    };
  
  
    return (
      &lt;Router&gt;
        &lt;div&gt;
          &lt;Navbar
            loggedIn={loggedIn}
            navMenuToggle={navMenuToggle}
  
          /&gt;
          &lt;NavMenu
            loggedIn={loggedIn}
            show={navMenuOpen}
            navMenuClose={navMenuClose}
            logoutFromNavMenu={logoutFromNavMenu}
          /&gt;
          &lt;Switch&gt;
            &lt;Route
              path="/login"
              render={(props) =&gt; (
                &lt;Login
                  handleLogin={handleLogin}
                  handleChange={handleChange}
                  email={email}
                  password={password}
                  errorMsg={errorMsg}
                /&gt;
              )}
            /&gt;
  
            &lt;Route
              path="/register"
              render={(props) =&gt; (
                &lt;Register
                  handleRegister={handleRegister}
                  handleChange={handleChange}
                  email={email}
                  username={username}
                  password={password}
                  password2={password2}
                  errorMsg={errorMsg}
                /&gt;
              )}
            /&gt;
  
            &lt;Route
              path="/profile"
              render={() =&gt; (loggedIn ? &lt;Profile /&gt; : &lt;Redirect to="/login" /&gt;)}
            /&gt;
  
            &lt;Route
              path="/thankyouForRegistering"
              render={() =&gt;
                authorized ? (
                  &lt;ThankyouForRegistering /&gt;
                ) : (
                  &lt;Redirect to="/register" /&gt;
                )
              }
            /&gt;
  
            &lt;Route
              path="/recipes"
              render={(props) =&gt;
                loggedIn ? &lt;RecipeBook /&gt; : &lt;Redirect to="/login" /&gt;
              }
            /&gt;
            &lt;Route
              path="/list"
              render={(props) =&gt;
                loggedIn ? &lt;ShoppingList /&gt; : &lt;Redirect to="/login" /&gt;
              }
            /&gt;
            &lt;Route path="/about" component={About} /&gt;
            &lt;Route path="/contact" component={Contact} /&gt;
  
            &lt;Route
              path="/accountSettings"
              render={(props) =&gt;
                loggedIn ? &lt;AccountSettings /&gt; : &lt;Redirect to="/login" /&gt;
              }
            /&gt;
  
  
            &lt;Route
              exact
              path="/"
              component={() =&gt; &lt;Home isLoggedIn={loggedIn} /&gt;}
            /&gt;
          &lt;/Switch&gt;
        &lt;/div&gt;
      &lt;/Router&gt;
    );
  }
  
  export default App;
  </code></pre>