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!
isAuthenticatedproperty in your Redux store is not synced with thelocalStorage? So if you reload the page, it will take the value in the default state, which isnull