2

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.

2
  • Have you tried dispatching your initAuth in componentWillMount? Commented Dec 2, 2016 at 16:08
  • 1
    @vwrobel I did, there's no difference on the first render the user isn't set already so it doesn't Match Commented Dec 2, 2016 at 16:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.