When using a ES6 Symbol
as the key for a key/value pair in LocalStorage
, can we then still access it after reloading the page?
I found this tutorial that claims this to be possible when using Symbol.for
, but so far I have no success and get an undefined
when I try to retrieve the LocalStorage key/value pair.
As a side question: does it make sense to use Symbols
over here?
You can use Symbols as keys in an object - that's ultimately their purpose. But
localStorage
is not your typical object. It has an API to set/get values in the store, which the tutorial you have shared is not using:localStorage.{set,get}Item()
.Unfortunately
localStorage
doesn't accept Symbols as keys, only strings. So the real answer is no, you can't use Symbols as keys in LocalStorage, but...You could do the following. It isn't actually using a Symbol as the key, but the Symbols
toString()
representation:[ Check it out on jsbin.com ]
I suppose you could use reserved Symbols (e.g.
Symbol.iterator
) to extend the functionality of thelocalStorage
global. But that's kind of besides the point.