Home > Software design >  <VirtualizedList> has duplicate key, but it shouldn't
<VirtualizedList> has duplicate key, but it shouldn't

Time:12-14

I am using in the following way:

<VirtualizedList
  onEndReachedThreshold={DEFAULT_THRESHOLD_VALUE}
  getItem={(data, index) => data[index]}
  getItemCount={(data) => data.length}
  keyExtractor={(item, index) => item.id   index}
  {...props}
  data={listData}
  onEndReached={getNextPageData}
  ListFooterComponent={footerComponentJsx}
/>

As you can see, for keyExtractor prop, I'm using the index as well as item.id, so I don't think I should get any duplicate keys. Yet, I get this error:

 ERROR  Warning: Each child in a list should have a unique "key" prop.

Can someone give me some insights on why this is happening and how to remedy this?

CodePudding user response:

It is because there are maybe the same keys for an item in your:

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

So be clear about item.id index is not the same for two item.

So do one thing give a unique id for each item in item.id and then use it as below:

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

CodePudding user response:

You can just add random number in it.

If you are sure that you have id in your item.

   keyExtractor={(item, index) => `${Number(item.id)   Number(index)}`}

If you are not sure that you have id in your item.

   keyExtractor={(item, index) => `${Math.random()   Number(index)}`}
  • Related