Last active
August 22, 2019 19:35
-
-
Save ccnokes/fc5ca4b215d08617b741a44586868d15 to your computer and use it in GitHub Desktop.
Sometimes in React you need a unique `key` to represent an object's identity. Instead of generating an id when you fetch it from an API or generating an id on the fly or using indexes (both will lead to bugs), you can use this which gives you a stable, unique id for an object. Demo: https://codesandbox.io/s/nice-gauss-h424o. Demo with React: htt…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let map = new WeakMap(); // weakly holds all object refs (works in IE11+) | |
let n = 0; // global counter for ids | |
export function idObj(obj: any) { | |
if (map.has(obj)) { | |
return map.get(obj); | |
} else { | |
let key = String(++n); | |
map.set(obj, key); | |
return key; | |
} | |
} | |
// test it out ... | |
let o1 = {}; | |
let o2 = {}; | |
console.log(idObj(o1)); // 1 | |
console.log(idObj(o2)); // 2 | |
console.log(idObj(o1)); // 1 | |
o1 = { a: 1 }; // re-assign it | |
o2.b = 13; // mutate this one | |
console.log(idObj(o1)); // 3 (because 1 is gone now) | |
console.log(idObj(o2)); // 2 (still the same object identity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this actually is usually a bad idea, don't do it 😅