I'm having some trouble with authentication with redux and react router and am hoping for some clarification on how to best solve my problem.
I have a login component that when submitted dispatches the following action:
export const loginUser = (creds) => {
return dispatch => {
dispatch(requestLogin(creds))
return fetch('http://127.0.0.1:4000/api/login', {
...
})
.then(res => {
dispatch(receiveLogin())
browserHistory.push('/admin')
...
})
...
}
}
The receiveLogin action updates the isAuthenticated flag in the state to true. My protected route has the following onEnter hook:
export default (state) => {
return {
path: '/',
component: App,
childRoutes: [
{
path: 'protected',
component: Protected,
...
onEnter(nextState, replaceState) {
const loggedIn = //check state.isAuthenticated
if (!loggedIn) {
replaceState(null, 'login')
}
}
}
]
}
}
As you can see, I am passing the state in as an argument. This gives me access to the initial state from the server as well as on the client. However, after my login action happens, obviously the onEnter hook will still be using the initial state.
What I want to know is the best way to get the current state after the isAuthenticated flag is updated and use that in my onEnter hook instead. Or, is my approach totally flawed and should I be doing this a different way entirely?