I am trying to have the url parameters determine which 'article' is loaded.
However the mapStateToProps is firing first, and causing the article data to come up undefined. So an error message is thrown before the componentDidMount can fire (which is what is suppose to load the article data into the state). I have tried putting the dispatch in other places (like in render or in its own method), still the same issue.
This is my comonentDidMount:
componentDidMount(){
const params = this.props.location.search.split('/');
this.props.dispatch(getArticleStats({articleId:params[4]}));
This is my mapStateToProps:
const mapStateToProps=(state)=>{
return {
user: state.user,
article: state.article
}
}
The error I am getting shows the data in state.article is undefined, since dispatch has not fired yet:
TypeError: Cannot read property 'articleTitle' of undefined
Any wisdom or guidance would be appreciated.
There is no way to make mapStateToProps
fire after the dispatch
call. mapStateToProps
is a argument to connect
which is a higher order component (HOC). This essentially makes your component a child in relation to the connect
function.
The solution to your problem is most likely not to reorder the call of dispatch
, but to handle the scenario where article
is still undefined. A simple falsy check will most likely do the job: if (this.props.article) ...