Reputation: 172
I've stumpled into a problem regarding localStorage. My code looks like this:
var defaultReportData = {
'station': 'DR P3',
'days': 'Mon, Tue, Wed, Thur, Fri',
'startHour': '06:00',
'endHour': '18:00',
'demography': 'Cover: All'
}
localStorage.setItem('defaultReportData', JSON.stringify(defaultReportData));
// Returns null
console.log(localStorage.getItem('station'));
Whenever I just type out "localStorage" in my console after loading the page, the object gets output correctly. However, the localStorage output returns null in my console when I want to get a specific value.
What am I doing wrong?
Upvotes: 4
Views: 13823
Reputation: 5698
It works, just copy and paste to your console
var defaultReportData = {
'station': 'DR P3',
'days': 'Mon, Tue, Wed, Thur, Fri',
'startHour': '06:00',
'endHour': '18:00',
'demography': 'Cover: All'
}
window.localStorage.setItem('defaultReportData', JSON.stringify(defaultReportData));
// Returns null
var itemPref = window.localStorage.getItem('defaultReportData')
var resultObject = JSON.parse(itemPref);
console.log(resultObject.station);
Upvotes: 1
Reputation: 7368
You have to retrieve data from localStorage using the same key
(defaultReportData) used at the time of storage and then parse the string data to JSON Object
var data=JSON.parse(localStorage.getItem('defaultReportData'));
console.log(data.station);
Upvotes: 2
Reputation: 67525
You've to parse the returned string to JSON to get the station
like :
var defaultReportData = JSON.parse(localStorage.getItem('defaultReportData'));
console.log( defaultReportData.station );
Upvotes: 6