React Native - Use a keyExtractor with FlatList

jdoej picture jdoej · Dec 23, 2017 · Viewed 65.9k times · Source

I have been getting the:

"VirtualizedList: missing keys for items, make sure to specify a key property on an item or provide a custom keyExtractor"

pretty confusing..., the array i am passing it has a key property defined in each object in the array. I have that array defined in this.state. I ran a quick print out in the console to be sure: print out of array

Each object in array is defined as:

  var obj = {key: doc.id, value: doc.data()};

(doc and data being from another part of my app, but I know doc.id is unique)

After some googling I then tried to define a Key Extractor like so:

_keyExtractor = (item, index) => item.key;

and then here is my flatlist definition:

  <FlatList
        style={{}}
        data={this.state.FeedDataCollection}
        keyExtractor={this._keyExtractor}
        renderItem={(rowData) =>this.RenderFeedCard(rowData)}
      />

Still receiving the same error, at this point not really sure how to handle this or what it is doing wrong. Any Ideas? Thanks so much!

Answer

Sarantis Tofas picture Sarantis Tofas · Dec 24, 2017

"VirtualizedList: missing keys for items, make sure to specify a key property on an item or provide a custom keyExtractor"

This is a warning that the elements of the list are missing keys. These unique keys are what allow the VirtualizedList (which is what FlatList is built on) to track items and are really important in terms of efficiency.

You will have to choose a unique key prop, like an id or an email.

The keyExtractor falls back to using the index by default. But the warning will remain visible.

Example : an object defined as {key: doc.id, value: doc.data()} can be used in the extractor as:

keyExtractor={(item, index) => item.key}

Flatlist component should look like that:

<FlatList
  style={{}}
  data={this.state.FeedDataCollection}
  keyExtractor={(item, index) => item.key}
  renderItem={(rowData) =>this.RenderFeedCard(rowData)}
/>