reactjsoptimistic

React: Unique keys and optimistic updating


In my React app I render an array of items returned from the server, using the database id's as keys.

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

This works fine, but now I want to do optimistic updating, so I insert new items into the array before submitting them to the server, and then add the database id when the post operation is done. Now my array briefly contains items with no id's causing errors due to the missing keys.

What to do? I know using the index as key is considered an anti-pattern (https://www.menubar.io/react-keys-index/), so that's out of the question. I also don't want to generate new unique id's for the items because then they will all have two unique id's once they have been saved to the database. I considered using random keys for the unsaved objects, but that seems like a precarious solution.

Is there a best practice solution for this situation? I can't be the first person to encounter this issue.


Solution

  • If you are only ever appending to the list you could use an id that is derived from the array index and is guaranteed to never collide with backend ids. Something like the index as a negative value if you have incrementing primary keys in your backend or a string `New-${index}`.

    Alternatively as you can't know the backend id in advance I don't see another solution else then using an uuid generator to temporarily generate an id for that item. Such an id is practically collision free.

    Using the index is very risky as one of the other items could already use that id.