0

My initialstate in redux store is

const initialState = {
  token:localStorage.getItem('token'),
  isAuthenticated: null,
  isLoading: false,
  user:null,


}

My app component looks like:store.dispatch(loadUser()); check the token of local storage and load user from API if token is exists and correct.

class App extends Component {
componentWillMount() {
  store.dispatch(loadUser());
}
render() {
  return (
    <div className="App">
      <Provider store={store}>        
      <Router>            
          <BaseRouter/>            
      </Router>
    </Provider>  
  </div>
 );
 }
}

export default App;

everything works fine, but when I reload component in browser it immediately redirect me to component, despite the redux dev tools shows that user is loaded and isAuthenticated:true.My question is : How I can load my redux store before render() function?? Or is there any other ideas to make it work correctly??

class ArticleList extends Component{
static propTypes = {
    articles: PropTypes.array.isRequired,
    getArticles: PropTypes.func.isRequired,
}

componentWillMount(){
    this.props.getArticles();
}
render(){
    console.log('is_auth',this.props.isAuthenticated);// console shows NULL
    if (!this.props.isAuthenticated) {
        return <Redirect to="/login" />;
      }
    return(
        <Fragment>
            <Articles data={this.props.articles}/>     
        </Fragment>
    )
  }
}
  const mapStateToProps = state =>({
articles: state.articleReducer.articles,
isAuthenticated: state.authReducer.isAuthenticated
})

 export default connect(mapStateToProps,{getArticles})(ArticleList);

Thank you in advance!

1
  • I assume that the isAuthenticated property in your Redux store is not synced with the localStorage ? So if you reload the page, it will take the value in the default state, which is null Commented Mar 11, 2019 at 15:44

1 Answer 1

1

ArticleList is being rendered even before isAuthenticated is updated as true. Hence the redirection is happening everytime. This can be solved by waiting the main router's render until authentication is complete. Eg :

function BaseRouter(props) {
  return !props.isLoading ? (
    <Router>
      <Route />
      <Route />
      <Route />
    </Router>
  ) : null;
}

const mapStateToProps = state => ({ isLoading: state.authReducer.isLoading });
export default connect(mapStateToProps)(BaseRouter);

This will block all routes till authentication check is complete. If you need to enable some routes which do not require authentication, apply conditional render.

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.