Daniel Barde
Daniel Barde

Reputation: 2703

React Router onEnter Error

i'm trying to add route authentication to my reactjs app on react router, but whenever I add the authentication function i created to the on enter property on the specific route i get the following error.

Uncaught RangeError: Maximum call stack size exceeded

My Routes

// libraries
import React from '../node_modules/react';
import {Router, Route, browserHistory, IndexRoute, Redirect} from '../node_modules/react-router';
// route middleware
import requiresAuth from '../middleware/requiresAuth';
// components
import App from '../modules/other/app.jsx'; 
import Dashboard from '../modules/stats/dashboard.jsx'; 
import Login from '../modules/auth/login.jsx';
import NotFound from '../modules/errors/notfound.jsx';
// routes
export const routes =
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Dashboard} onEnter={requiresAuth} />
            <Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requiresAuth} />
            <Route path="login" name="login" component={Login} />
            <Route path="*" name="notfound" component={NotFound} />
        </Route>
    </Router>;

My authentication function

const requiresAuth = (nextState, replace) => {
    if (!loggedIn()) {
        replace({
            path: '/login',
            state: {next: nextState.location.pathname}
        });
    }
}

const loggedIn = () => {
    return !!localStorage.token;
}

export default requiresAuth;

Upvotes: 3

Views: 418

Answers (2)

Dhruv Kumar Jha
Dhruv Kumar Jha

Reputation: 6571

To fix the error, You have to change your replace code from

replace({
    path: '/login',
    state: {next: nextState.location.pathname}
});

To

replace({
  pathname: '/login',
  state: {nextPathname: nextState.location.pathname}
});

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281616

Try and make a change to how localStorage.token is returned.

const loggedIn = () => {
    return localStorage.token;
}

Upvotes: 1

Related Questions