React.js: how to generate a key when creating an optimistic creation?

Working with React.js is really enjoyable.

I created a simple commentary application based on the official tutorial.

You can add, edit and delete comments. They are pulled through the GET every 10 seconds.

At some point, optimistic updates are mentioned in the manual: updating the user interface before the server responds in case of a create, update or delete operation.

Because comments are part of the list, React suggests assigning a unique key to each comment.

Therefore, I use the database identifier of each comment as a key. This works great for update and delete operations.

However, in the case of the create operation, I do not know the comment database identifier until it was actually created on the server side, and therefore I do not know what value to assign to the key.

At this point, the comment is added to the comment list but does not have a key / identifier and therefore cannot be edited or deleted until the list is updated during the next API poll.

Can I get around this?

+6
source share
3 answers

You can add, edit and delete comments. They are pulled through the GET every 10 seconds.

We always send a POST to the resource, which as a result returns a JSON response containing the data that we need in your case identifier. The delay is up to ~ 100 ms, which is good.

If you set a temporary identifier that is not equal to that provided by one database, React will repeat the visualization again as soon as it receives new data, you will just see two identical elements, because the key does not match.

-2
source

If you want the key to remain unchanged for all updates, one option is to assign a temporary identifier to an unused property. Then use the function to get the correct key for your list item models. As long as you take into account the tempId property when updating the item, you can keep the key the same as long as the list remains in memory.

While you may not like deleting the optimized element and re-adding it, it can simplify your CSS by using on-enter or on-leave animations in your list. It also helps when you have state list item components.

Example:

let tempIds = 1; // 1 and up are truthy // where ever you add the new item to your list const newList = [...list, {...newItem, tempId: tempIds++}]; // get the right id function getKey(instance) { if (instance.tempId) { return instance.tempId; } else { return instance.id; } } // in your list render function <List> {list.map(model => ( <Item key={getKey(model)} //other props go here /> ))} </List 
+2
source

You need keys that are unique, consistent, and accessible. Database identifiers cannot provide the third requirement, but you can - use local "client identifiers". Obviously, you are responsible for their uniqueness and consistency.

0
source

All Articles