typescript:S6479 fails to account for keys that include other values with an index

Typescript rule S6479 warns us not to use indexes for keys in arrays, but does not take into account when a key uses both an index and another value.

True positive:

{items.map((item, index) => <Item key={index} item={item} />

False positive:

{items.map((item, index) => <Item key={`${item.id}-${index}`} item={item} />

The first situation doesn’t take into account the content being rendered, which is a problem. If the content changes, but the key doesn’t, React won’t know and not rerender it.

The second situation arises when there are duplicate items in an array, which can happen in lists of text strings or non-DB-derived objects, for example. In this situation, the index is required to prevent React from throwing up duplicate key errors. By combining the index with the key, we sacrifice order-agnostic memoization for uniqueness. This is preferable to breaking React’s requirement of unique keys.

I’d recommend tightening the scope of TS:6479 to keys that are index-only. If another variable associated with the element in the array is included, that should be acceptable. I don’t know if the parser can get that specific, or if it is enough to say “another variable is referenced,” but this seems a valid alternative.

1 Like

Hello @lunarlandis,

Thank you for taking the time to provide your valuable feedback, and a warm welcome to the Sonar community!

Your scenario highlights a pertinent use case that our rule should encompass. To address this, I have created a ticket to introduce a specific exception for this case.

We are committed to addressing it promptly.

Best regards,
Yassin

1 Like

Thank you! :slight_smile:

Yes this rule as-is is just an incomplete idea! It’s great to use content rather than index as a key when possible, but of course it is not always possible with unique keys, in which case index is necessary. Total oversight.

Hey @zsiegel92 !

A fix was merged for this a year ago. What version of SonarQube are you using?

Using Sonar Cloud

Thanks! Can you share a code sample where you’re facing the issue?