I am in progress of migrating my app to from react-router-redux
-to --> connected-react-router
however, I'm seeing an issue. Currently, I have certain routes that are protected(requires authed users) i.e dashboard
export default function Routes(props, context) {
return (
<Switch>
<Route exact path="/" component={Login} />
<Route path="/login" component={Login} />
<Route
render={props => <Authorization {...props} routes={AuthRoutes} />}
/>
</Switch>
)
}
const AuthRoutes = [
<Switch>
<Route path="/dashboard" component={Dashboard} />,
<Route component={Error404} />
</Switch>,
]
The Authorization component looks like:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Redirect, withRouter } from 'react-router'
class Authorization extends Component {
isAuthenticated() {
const { auth, app } = this.props
const { search } = app
console.log('====================================')
console.log('Auth:', auth)
console.log('====================================')
if (auth && auth.token) {
return this.props.routes.map((route, index) =>
React.cloneElement(route, { key: index })
)
} else {
return <Redirect to={{ pathname: '/login', search }} />
}
}
render() {
return <div style={{ width: '100%' }}>{this.isAuthenticated()}</div>
}
}
export default connect(state => ({
auth: state.auth,
app: state.app,
}))(withRouter(Authorization))
After user logs in he is directed to /dashboard
path and token
is saved to auth in redux store(which is persisted to localStorage).
THE ISSUE:
- Upon 1st page refresh, console.log statement(from Authorization)
outputs that
Auth: {token: null}
and the user redirected to/login
- Upon 2nd refresh console.log statement(from Authorization) outputs
that
Auth: {token: <userToken>}
and the user redirected to/dashboard
(correct behavior) - Upon 3rd refresh console.log statement(from Authorization) outputs
that
Auth: {token: null}
and the user redirected to/login
- Upon 4th refresh console.log statement(from Authorization) outputs
that
Auth: {token: <userToken>}
and the user redirected to/dashboard
(correct behavior)
Notice a pattern? It seems the Authorization
component on every other page refresh access the auth state before it has had time to restore from local storage.
If I revert back to using react-router-redux
the user is redirected to /dashboard
correctly at each page refresh after login.