Reputation: 15
I've been trying to figure out how can I pass value from state (personId) to function (fetchPersonInfo) as a parameter, but nothing that I've tried has yet to work. So I thought to come ask your help with this.
class Page extends Component {
state = {
personId: '',
}
componentDidUpdate = () => {
if(this.props.results.length > 0 && this.state.personId !== this.props.results[0].results[0].id){
if(this.props.results[0].results[0].media_type === 'person'){
this.setState({personId: this.props.results[0].results[0].id});
this.personInfo(personId);
}
}
}
personInfo = (personId) => {
if(this.state.personId.length > 0){
this.props.fetchPersonInfo(personId);
}
}
}
Upvotes: 0
Views: 67
Reputation: 8652
React setState
is asynchronous, you cannot call personInfo()
in a sync way as you're doing
this.setState({personId: this.props.results[0].results[0].id});
this.personInfo(personId);
assuming the rest of the code is fine, change the above code to
this.setState({personId: this.props.results[0].results[0].id}, this.personInfo);
and remove personId parameter from the function
personInfo = () => {
if(this.state.personId){
this.props.fetchPersonInfo(this.state.personId);
}
}
Upvotes: 2
Reputation: 156
The error is here:
this.setState({personId: this.props.results[0].results[0].id});
this.personInfo(personId);
Call the persionInfo in this way: this.personInfo(this.props.results[0].results[0].id)
Or:
this.props.fetchPersonInfo(this.state.personId);
Upvotes: 0