DEV Community

Discussion on: 9 Neat JavaScript Snippets For Algorithms And More

Collapse
 
dcsan profile image
dc

With your code to generate IDs won't that break the react rendering if the ID is generated differently each time? I thought the point was that the key for component is derived from the actual data so that it is always going to be the same key for the same item in a list or whatever?

Maybe a few components are always called and rendered in the same order so then you get lucky and the counter for the key always returns the same value for the same invocation?

Collapse
 
mostlyfocusedmike profile image
Mike Cronin

No you're right, that would be a problem (and technically why we shouldn't use the map index as a key). That's not quite how it was used. Say you had real entries from a db like:

{ 
  id: 132,
  name: 'Tom',
  age: 31
}
Enter fullscreen mode Exit fullscreen mode

When mapping through them after fetching, you could use the ID as a key, since it should be unique and unchanging to its owner. My issue was, I was generating multiple items on the frontend BEFORE saving them as a batch. So that meant there was no id from a DB yet. So i just wanted a pre-id that was created with the object and didn't change. I used the counter method on initial generation, not iteration. Does that make sense?

Collapse
 
mostlyfocusedmike profile image
Mike Cronin

Also, yesterday what I used the counter for was making sure at least 3 resources had loaded onto a page. I didn't care in what order, just that 3 had loaded. So I used the counter on each load event, and once it hit three, any one of them could trigger the next function, but only one of them ever would. I thought that was neat.