Understanding how temporary IDs are used
I've got a function like
which I use when I insert new objects into my electric collections, even though the IDs end up being autogenerated on the DB. I sometimes see a little flicker in the UI as the tx is confirmed and the "new" ID (presumably) comes in. I also sometimes have issues where I try to delete an object and get a 404 on my backend because it's trying to delete something with a temporary (negative) ID. I think I just don't quite understand how the temp ID being replaced happens and how that affects react's behavior. If anyone has any light to shed on it I'd appreciate it!
5 Replies
conventional-tan•5d ago
basically the optimistic new object is replaced by the new object when it's synced back. The flicker can happen because React is removing the old object and putting in a new one.
For the delete problem — you should probably just disable any delete buttons/links until the new object has been persisted
harsh-harlequinOP•5d ago
got it, that's pretty much what I thought was happening. is there a workaround to react re-rendering? I guess avoid using the db/temp IDs as keys, but then I need to store something else that's stable
conventional-tan•5d ago
yeah, you can maintain a "ViewKey" that you always use and map to it the temp key & real key when it's returned — that'll keep the render stable
harsh-harlequinOP•4d ago
makes sense, thanks! I assume that's probably out of scope in terms of smth you'd consider adding to live collections? it seems like it might be a common workflow but at the same time I suppose it's not exactly related to the core feature set
conventional-tan•4d ago
GitHub
Support for Stable ViewKeys to Prevent UI Re-renders on ID Mapping ...
Problem Currently, optimistic inserts use temporary IDs (tempid) until the server responds with the authoritative ID (realid). When the ID changes, React re-renders the keyed element, causing UI is...