In my frontend, I'm working with a lot of entities which have an id: number
. IDs of course are given by the database, but I need some ID to work with unsaved entities.
I need temporary IDs because the view I'm working on consists of a number of different entities from the server, where more can be added into the view. I then have a big payload with existing and nonexisting entities that can all be modified before they are all sent to the server. Since I would like to treat them the same, I generally use the ID to find the object, and mutate in redux. I use a discriminator to declare which entities are novel, so the server doesn't care about the ID i send it.
Generating a string id with nanoid
or uuid
is simple of course, but how to reliably generate a number that doesn't exist yet?
I don't want to change my interface to allow id: string | number
because I would have to verify the type everywhere I'm using id.
My solution was to make negative ids like -1
, -2
etc. as the server wouldn't make those. But its still annoying having to check the array to make sure the number doesn't exist yet.
Is it ok to have a single generator function provide negative ids?
Or should I just dump number ids and migrate my db to strings? (Not preferred of course as my db is running, but I could see the benefit)
question from:
https://stackoverflow.com/questions/65875594/how-to-do-temporary-number-ids-in-the-frontend 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…