Search code examples
react-routerreact-hooksuse-effect

How to change router in React useEffect


I tried to combine react-router-dom with useEffect, I tried to change router after logging in, here's my code

const Member = () => {
  let history = useHistory(); 

  useEffect(()=>{
      if(!signInStatus.current){
          return 
      }
      signIn(sign_data) //async fetch api
      .then(response=>{ 
        if(response.status!==200){
          setSigninError(response.message)
        }else{
          window.alert("Welcome")
          history.push('/signup') //just test 
          //change route
        }
    })
    .then(data=>signInStatus.current = false)
  })'
  return (
    <BrowserRouter>
        <Switch>
            <Route path="/signup" render={()=>{return(
            <div className="app"><Header /><SignUp add={setData} submittingStatus={submittingStatus} error={signupError}/></div>)}}/>
            <Route exact path="/" render={()=>{return(
            <div className="app"><Header /><SignIn sign={setSign} signInStatus={signInStatus} error={signInError}/></div>)}}/>
        </Switch>
    </BrowserRouter>    

So after I did some research,I think this won't work is due to the router hasn't been render yet, since I write the router in the same page, so I wonder if there's any way to do router changing after useEffect. There's like a thousand way on stack overflow ,but they are all different versions , even with self-made hook. so I hope to get a custom answer , thanks very much!


Solution

  • I understand that you want redirection based on if the user has logged in or not.

    <Route exact path='/'>
              <Route
          render={() => {
            if (isAuthenticated) {
              return <HomePage />;
            } else {
              return (
                <Redirect
                  to={{
                    pathname: "/login",
                  }}
                />
              );
            }
          }}
        />
            </Route>
    

    In the useEffect you can check if the user has logged in or not. If yes then set the value of isAuthenticated to true, and the redirection will be handled authomatically.

    With this example you can redirect the user to /login if he is not logged in and tries to reach the homepage. Hope this is a similar example to your query. If any confusions do ask.