Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't localStorage accepting my object? [duplicate]

I need to store an object like the one I the example below in localstorage. I need to be able to retrieve this object and edit it, then save it back into localStorage for next time.

var data = {lastEdit:"September", expires:"December", records:[{arrives: "12:45", departs: "12:51"}, {arrives: "13:03", departs: "13:04"}]};

I tried this but it said 'undefined':

localStorage.setItem("dataStore1", data);
var output = localStorage.getItem("dataStore1");

What can I do to fix it?

Solved

like image 961
Jamie W Avatar asked Oct 18 '17 14:10

Jamie W


2 Answers

From Using the Web Storage API:

"Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do)."

You cannot store a complex Object value in localStorage. Sorry.

Instead, you should serialize your Object as a string [hint: JSON.stringify()] and then after retrieving it parse from JSON string back to Object [hint: JSON.parse()].

like image 20
Phrogz Avatar answered Oct 24 '22 07:10

Phrogz


Use JSON.stringify() to set JSON and JSON.parse() to convert JSON to a JavaScript object; localStorage expects a string to be set.

like image 84
guest271314 Avatar answered Oct 24 '22 07:10

guest271314