I have a FlatList that displays a user's comments and I want to also populate the header with the user's profile (which is a different network call from the one fetching the comments).
Here's how render() looks like:
render() {
return (
<FlatList
data = {this.state.comments}
renderItem = {this.renderComment}
ListHeaderComponent={this.renderHeader}
keyExtractor={(comment, index) => comment.id}
/>
)
}
and then renderHeader looks like:
renderHeader() {
return (
<ProfileView user={this.state.profile} />
)
}
I use fetch in componentWillMount and then setState in order to get the data (this part works fine).
Now the error I get on the simulator is
undefined is not an object (evaluating 'this.state.profile')
but when I remove the renderHeader method, comments are fetched properly.
Since I'm very new to RN, can you help me understand what is wrong and how to fix it?
This looks like simply an issue with accessing context. When you run the renderHeader method called by the FlatList it doesn't know what this relates to.
So, you can simply set this.renderHeader = this.renderHeader.bind(this) in your constructor() method.
Alternatively, you should also be able to use an arrow function to call it, as this automatically refers to the correct this context.
ListHeaderComponent={() => this.renderHeader()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With