Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a FlatList's header with data from the network?

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?

like image 922
phi Avatar asked Jun 07 '17 15:06

phi


1 Answers

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()}
like image 69
G0dsquad Avatar answered Jan 03 '23 19:01

G0dsquad