2

I'm using React Router v4 Browser Router. My scenario is I have call login page on every page refresh (Browser Refresh click or F5)

Route

 <Router history={history}>
        <div>
          <Spin spinning={this.props.isloading}>
            <Switch>
              <Route path="/login" component={Login} />
              <Route path="/Dashboard" component={Dashboard} />
              <Route path='*' component={NotFound} />
            </Switch>
          </Spin>
        </div>
      </Router>

I need to load login component on page refresh so I need something like below

<Refresh path="/login" component={Login} />
Maria Jeysingh Anbu
  • 3,164
  • 3
  • 34
  • 55
  • I think I answered your question; however, I honestly can't understand why you'd ever want to detect if the user refreshes the page. If I reloaded a page and the page displayed something differently, not because there's an update, but because I clicked refresh, I feel like that behavior diminishes the user experience somewhat. – Kevin Raoofi Apr 26 '18 at 21:44

3 Answers3

2

It happens to me and the issue was i am importing Router from react-router-dom instead of BrowserRouter as Router.

Pawan Bishnoi
  • 1,759
  • 8
  • 19
0

Create a componentDidMount method in your root component, which will be responsible for logging in your user by redirecting the user to /login.

Then add a event listener for page refresh which will logout the user for any page refresh.

componentDidMount(){
    if(!userLoggedIn()){
        //redirect to login
        history.push("/login")
    }

    window.addEventListener('beforeunload', logoutTheUser);
    /* if you are not maintaining a session, you dont need this
      as user will be logged out automatically on page refresh.*/
}
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
  • `window.addEventListener('beforeunload', logoutTheUser); `It is getting called even I switch pages. I need to call only on page refresh not on changing menus – Maria Jeysingh Anbu Apr 26 '18 at 21:17
0

Just do something like:

const Refresh = ({reload, children}) => reload ? children : null;

...

<Refresh reload={performance.navigation.type === 1}>
    <Redirect to="/login"/>
</Refresh>

Based on:

Kevin Raoofi
  • 1,023
  • 11
  • 16