Lakshaya U.
Lakshaya U.

Reputation: 1171

localStorage returns as undefined but works with console

I wrote a JavaScript file which reads history from localStorage and logs it to the console. The value of the key history is a string array which looks somthing like this:

[
  {
    "dateCreated": 1624953025609,
    "link": "localhost/97a4",
    "uri": "google.com"
  }
]

and as expected the key/value also shows up in the Application DevTools tab. I can also access the array in the console after JSON.parse()ing it like:

JSON.parse(localStorage.getItem("history"))[0].dateCreated;
// 1624953025609

. However, another JS file which looks like

function checkLocalStorage() {
    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem('feature_test', 'yes');
            if (localStorage.getItem('feature_test') === 'yes') {
                localStorage.removeItem('feature_test');
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    } else {
        return false;
    }
}

var isEnabledLocalStorage = checkLocalStorage();

if (!isEnabledLocalStorage) {
    $('<p></p>').append("Your browser doesn't support <b>localStorage</b> or it is disabled.<br><b>localStorage</b> is required to view your history.")
} else {
    var history = JSON.parse(localStorage.getItem("history"))[0];
    document.write(history.dateCreated);
}

writes undefined to the document. How do I get the value of a nested object from the history localStorage key?

Upvotes: 0

Views: 626

Answers (1)

LuisAFK
LuisAFK

Reputation: 957

It is undefined because in your else statement, you call your variable history, but that already exists: window.history
So instead of saving the parsed JSON, it fails to overwrite and when you retrieve the dateCreated property, it doesn't exist on window.history.

Just rename your variable to something like saved_history.

Upvotes: 2

Related Questions