HTML5 localStorage design questions
-
26-09-2019 - |
Question
What is the best way to store object data in HTML5's localStorage. I haven't worked much with key value storage.
In my research i've seen a few different approaches.
example data:
var commands = [
{invokes: 'Window', type: 'file', data: '/data/1'},
{invokes: 'Action', type: 'icon', data: '/data/2'},
{invokes: 'Window', type: 'file', data: '/data/3'}
];
Approach 1: store keys that represent each data item
// for(...) {
localStorage["command[" + i + "].invokes"] = command[i].invokes
localStorage["command[" + i + "].type"] = command[i].type
localStorage["command[" + i + "].data"] = command[i].data
//}
Approach 2: keys is entity name, store json
localStorage["commands"] = JSON.stringify(commands);
Second approach would require a JSON.parse().
pros/cons?
Solution
For the record I went with approach 2. My key is similar to a table name, the value is a json stringified array of records. When retrieving the table you must call JSON.parse().
OTHER TIPS
technologies for local storages are: http://madhukaudantha.blogspot.com/2011/02/client-side-storages-with-html-5.html...
Approach 2, OK.. there are more ways
Certainly your approach works just fine however it does leave you a bit stuck with the convention you chose moving forward. I would recommend that you consider wrapping your localStorage access up in a class so that your convention is isolated to a class as a true convention.
Otherwise should you chose to change ho you approach it you will have implementation code scattered all over your code base.