BravoZulu
BravoZulu

Reputation: 1140

React-Router v4 and Redux authentication

I'm using react-router v4 and Redux for a new project.

I have the following code:

export class App extends Component {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(initAuth());
  }

  render() {
    const { user } = this.props;
    return (
      <BrowserRouter>
        <div>
          <NavContainer />
          <Match pattern="/login" component={LogInForm} />
          <MatchWhenAuthorized pattern='/users' component={Users} user={user} />
        </div>
      </BrowserRouter>
    );
  }
}

Where initAuth dispatches an action that checks if there's an existing token in localStorage and if there is, a logIn action is dispatched as well.

The problem is that if I go directly to myapp.com/users the action hasn't returned yet, so there's no user logged in and in that case MatchWhenAuthorized redirects me to my LogInForm, which I don't want if my initAuth logs a user in.

Is there an elegant way to solve this?

I think I could solve it by rendering the MatchWhenAuthorized component only if there's a user logged in, but that doesn't seem right.

Upvotes: 2

Views: 1318

Answers (1)

Paul S
Paul S

Reputation: 36787

The initial login state should be set when the page is loaded and before you mount your app. I'm not sure why the initAuth is a redux action creator when you could just check the localStorage without involving redux.

index.js

import { createStore } from 'redux'
import reducer from './reducer'
import { getUser } from './storage'

// load the user data from localStorage and
// use the value in the store's initial data
const store = createStore(reducer, {
  user: getUser()
})

Then you can connect your <MatchWhenAuthorized> component to the store to access the user value and redirect if there is no user in the store.

Upvotes: 2

Related Questions