I\'m trying to store multiple pieces of data in localStorage. However, only one piece is being stored and I can\'t figure out why. Here\'s the code
You're overwriting lastname
every time you call setItem
, so the last one (saving "Jones"
) wins.
If you want to save more than one item, either:
Use a different key (lastname1
, lastname2
, ...), or
Store a string in some format you can parse into individual items, for instance an array that you JSON.stringify
when storing and JSON.parse
when loading
Side note: Sadly, that typeof
check is not adequate to determine whether you can use localStorage
, because on some browsers in private browsing mode, typeof
will say it's there but it'll throw an error when you try to save something. The only way to know for sure is to actually try to save something:
// Once on page load
const canUseStorage = typeof localStorage !== "undefined" && (() {
const key = "_test_storage";
const now = String(Date.now());
try {
localStorage.setItem(key, now);
const flag = localStorage.getItem(key) === now;
try {
localStorage.removeItem(key);
} catch (e) {
}
return flag;
} catch (e) {
return false;
}
})();
// Then use `canUseStorage` as necessary to decide if you can use it
(Also note that typeof
is an operator, not a function. No need for parens around its operand.)