Using Key with hit item in react-native list

Hey guys, I was wondering how to properly use the key property with a hit component. I created a component to search the app’s users and provide a listItem that either renders an add button or added button next to the user. Without a key prop to ensure each item is unique, the buttons do not render appropriately. However, when I added a key prop, the search behavior no longer works properly. In my Dashboard, I have first name and last name as searchable attributes. I’m up-to-date using version 3.3.1 Thank you for any insight you can provide. Also, if there is a more appropriate place for me to post this, please direct me where and I’ll post accordingly.

class Hits extends React.Component {

  onEndReached() {
    if (this.props.hasMore) {
      this.props.refine();
    }
  }

  render() {
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    const hits = this.props.hits.length > 0 ?
      <View>
        <ListView
          dataSource={ds.cloneWithRows(this.props.hits)}
          renderRow={this.renderRow}
          onEndReached={this.onEndReached.bind(this)}/>
      </View> : null;
    return hits;
  };

  renderRow(hit) {
    const objectID = hit.objectID
    return < SearchListItem hit={hit} key={objectID} />
  }

};

Hey @adamjnavarro, you’re in the right place :thumbsup:

One favor to ask - can you see about updating the post so the code is in a formatted block. Makes it easier for us to review. Thanks!

Can’t you always use the objectID as the key? That should be unique

Forgive me if I’m misunderstanding what you mean, but I am using the objectID as the key value. It’s when I do that, that the search no longer works. In the screenshots, you can see that Dane should be the targeted hit but Shane is shown when ‘Dan’ is entered in the search input.

If I do not use a key prop, the behavior is odd as well. It seems that the button is rendered relative to the position of the list item. Using those screenshots, if I entered ‘Dan’ in the search input it would properly query but the button would show as Add rather than Added. No matter what user was shown in the first list item position, it would have an Add button regardless if the user had been added already.

I went for some help in the Expo slack channel, thinking it may be a problem with my react-native code and the responses I got were all pointing to the need of a key prop with a unique value.

That seems really odd, there is no way for a duplicate ObjectID to exist in Algolia, in fact, you can’t even push a duplicate one, so they’re definitely unique.

Sorry for misunderstanding your issue the first time by the way.

Is there someway I can run some reproducible example (as small as possible) that shows this type of error?

Hope I can help!