Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active August 22, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/fc5ca4b215d08617b741a44586868d15 to your computer and use it in GitHub Desktop.
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…
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)
@ccnokes
Copy link
Author

ccnokes commented Aug 22, 2019

this actually is usually a bad idea, don't do it 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment