How do I fill the FlatList header with data from the web?

I have FlatList

one that displays user comments and I want to also populate the header with the user profile (which is another net call from the one that picks the comments).

This is what it looks like render()

:

render() {
    return (
      <FlatList
        data = {this.state.comments}
        renderItem = {this.renderComment}
        ListHeaderComponent={this.renderHeader}
        keyExtractor={(comment, index) => comment.id}
      />
    )
  }

      

and then renderHeader

looks like this:

  renderHeader() {
     return (
      <ProfileView user={this.state.profile} />
    )
  }

      

I use fetch

in componentWillMount

and then setState

to get data (this part works fine). Now the error I am getting on the simulator is -

undefined is not an object (score "this.state.profile")

but when I remove the method renderHeader

, the comments are received correctly.

Since I am very new to RN, can you help me understand what is wrong and how to fix it?

+3


source to share


1 answer


It looks like a problem with accessing the context. When you run a method renderHeader

called FlatList

, it doesn't know what it refers to this

.

So, you can just install this.renderHeader = this.renderHeader.bind(this)

in your method constructor()

.



Alternatively, you can also use the arrow function to call, as this automatically references the correct context this

.

ListHeaderComponent={() => this.renderHeader()}

      

+7


source







All Articles