Fellow Stranger
Fellow Stranger

Reputation: 34013

Run function and redirect

I want to be able to type /logout in the address bar of the browser, and upon submit reset localstorage and redirect the user to /login.

I'm imagining something like this:

<Switch>
  <Route path="/logout">
    {clearAuthInLocalstorage()}
    <Redirect to="/login" />
  </Route>
</Switch>

How do I correctly declare this with react-router in a Switch container?

Upvotes: 0

Views: 34

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can create a Logout component and in componentDidMount lifecycle hook, you can do all the processing

class Logout extends Component {
  state = { loading : true };
  componentDidMount = () => {
    // clear localStorage here 
    this.props.history.push('/login');
  };
  
  return (
    <div className="page">
       <i className="laoder fas fa-spinner fa-spin" />
    </div>
  );
}

<Switch>
  <Route exact path="/login" component={Login} />
  <Route exact path="/logout" component={Logout} />
</Switch>

Upvotes: 1

Related Questions