Home > Blockchain >  Should I use database id or create new temporary id as key for React row
Should I use database id or create new temporary id as key for React row

Time:07-12

I'm making a table with React, where the user can add new entries, and I'm deciding what to use as a key. I'm considering these options:

  1. Use database id. But this will force me to talk with the server every time the user wants to add a new entry, which is not ideal.
  2. Generate a front-end id for each row and persist it in the state

Option 2 clearly seems better, but I see the React docs recommend using database id.

I've dealt with this same dilemma many times over different projects, and I've never figured out the best solution, so I decided to get it answered once and for all.

CodePudding user response:

It sounds like you might want to go with Option 2 for any data that hasn't been saved yet to the DB.

Recommendation is correct to use the DB id when available, but seeing as how your requirements allow for temporary or "draft" entries then I see no problem with Option 2. Just be wary of how you generate these temp ID's as you'll want to prevent clashes with existing ID's in the array.

CodePudding user response:

The answer posted by @Chris goes into much more detail.

also you can check react key docs .

  • Related