Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage returns NULL

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?

like image 507
Christian Futtrup Avatar asked Oct 14 '25 08:10

Christian Futtrup


2 Answers

Working Live example.

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 );
like image 101
Zakaria Acharki Avatar answered Oct 18 '25 05:10

Zakaria Acharki


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);
like image 28
NullPointer Avatar answered Oct 18 '25 07:10

NullPointer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!