I'm making a website with React, React Router, and Redux. Lots of routes (pages) require users to be logged in. I can redirect to the login page if the user is not logged in like this:
function requireAuth(nextState, replace) {
let loggedIn = store.getState().AppReducer.UserReducer.loggedIn;
if(!loggedIn) {
replace({
pathname: '/login',
state: {
nextpathname: nextState.location.pathname
}
});
}
}
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path=/ component={App}>
<IndexRoute component={Index} />
<Route path=login component={Login} />
<Route path=register component={Register} />
<Route path=dashboard component={Graph} onEnter={requireAuth}>
... some other route requires logged in ...
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('entry')
);
Please see the code, I used the onEnter hook to redirect to the '/login' route if the user is not logged in. Data for checking if the user is logged in is in the store and it will update after the user logs in.
It's working perfectly, but the problem is when I refresh the page, the store is reset and the user is not logged in state back.
I know this happens because the Redux store is just memory storage, so refreshing the page will lose all data from the store.
Checking the server session on every refresh may work but this might be too many requests, so that seems like a bad idea.
Saving the logged in state data to localStorage might work, but in this case, I should check every AJAX calls fail that request rejected because session is expired or not exists like something, and that seems like a bad idea too.
Is there a way to solve this problem more simply? My website needs to handle lots of users so I want to reduce XHR calls as much as possible.
Any advice will be very appreciated.