jacobsowles
jacobsowles

Reputation: 3003

React Router requireAuth not redirecting

I have the following routes and requireAuth implementation. I have two problems.

1.) I'm not being redirected from / to /login when I'm not logged in.

2.) The Home component isn't being rendered when I try to access / and I am logged in.

No console errors are showing up in any use case. I've confirmed that IsLoggedIn() is returning the expected value at the expected times. So my requireAuth implementation is likely to blame here. What did I do wrong?

index.js

import { isLoggedIn } from './auth';

function requireAuth(nextState, replace, callback) {
    if (!isLoggedIn()) {
        replace('/login');
    }
}

render(
    <Provider store={store}>
        <Router history={hashHistory}>
            <Route path="/" component={Home} onEnter={requireAuth} />
            <Route path="/login" component={Login} />
        </Router>
    </Provider>, document.getElementById('root')
);

auth.js

module.exports = {
    isLoggedIn() {
        return localStorage.token != undefined;
    }
};

Upvotes: 0

Views: 1482

Answers (1)

Igorsvee
Igorsvee

Reputation: 4211

If callback is listed as a 3th argument, this hook will run asynchronously, and the transition will block until callback is called. In your case, the callback is not needed and you can safely omit it(as the isLoggedIn is synchronous)

Upvotes: 4

Related Questions