Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

node.js - How to do temporary number IDs in the frontend?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...