Rian Halabi
Rian Halabi

Reputation: 107

How to correctly redirect after the user clicked logout

the app function have a router and i well use them in the components thanks for help ....

function App() {
  return (
    <Router>
      <div className='App'>
        <Switch>
          <Route exact path='/'>
            <Login />
          </Route>

          <Route path='/SignUp'>
            <SignUp />
          </Route>
        </Switch>
        <Route
          path='/Student/:id'
          exact
          render={({ match }) => <Student match={match} />}
        />
        <Route
          path='/Admin/:id'
          exact
          render={({ match }) => <Admin match={match} />}
        />
      </div>
    </Router>
  );
}

export default App;

just need to use redirect after the admin decided to click on the logout button without using usehistory.

const Admin = () => {
  const logoutfunc = async () => {
    let connectToServer = new ConnectToServer();
    //let session=await connectToServer.getSession()
    connectToServer.logout();
  };

  const redirect = () => {
    return <Redirect to={{ pathname: '/' }} />;
  };

  return (
    <div>
      <button
        onClick={() => {
          logoutfunc();
          redirect();
        }}
      >
        logout
      </button>
      <Cards />
      <TableStudent />
      <Cohorts />
    </div>
  );
};

export default Admin;

Upvotes: 2

Views: 3575

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

what you have to do is this:

const Admin = () => {
  const [redirect, setRedirect] = useState(false);
  const logoutfunc = async () => {
    let connectToServer = new ConnectToServer();
    //let session=await connectToServer.getSession()
    connectToServer.logout();
    setRedirect(true);
  };

  if(redirect){
    return <Redirect to={{ pathname: '/' }} />;
  };

  return (
    <div>
      <button
        onClick={logoutfunc}
      >
        logout
      </button>
    </div>
  );
};

or use push method like this:

const Admin = () => {
  const logoutfunc = async () => {
    let connectToServer = new ConnectToServer();
    //let session=await connectToServer.getSession()
    connectToServer.logout();
    history.push({ pathname: '/' })
  };

  return (
    <div>
      <button
        onClick={logoutfunc}
      >
        logout
      </button>
    </div>
  );
};

Upvotes: 1

Related Questions