When using setItem, the value is turned into a string before being stored. It does this using the given value's .toString() method (every data type has this method).
As you can see, this is particularly annoying when dealing with Arrays and Objects because of the way that they get turned into strings.
const num = 13;
const bool = true;
const str = 'purple';
const arr = [1, 2, 3];
const obj = { name: 'ben' };
console.log(num.toString()); // '13'
console.log(bool.toString()); // 'true'
console.log(str.toString()); // 'purple'
console.log(arr.toString()); // '1,2,3' <-- mildly annoying that the [] are gone
console.log(obj.toString()); // '[object Object]' <-- what is this garbage??
// JSON.stringify() is much better
console.log(JSON.stringify(arr)); // [1, 2, 3]
console.log(JSON.stringify(obj)); // { name: 'ben' }
However, the JSON.stringify() method preserves the structure of Arrays and Objects.
Stringify and Parse
Before storing values in localStorage, we should JSON.stringify() them.
const instructors = ['ben', 'gonzalo', 'motun', 'zo', 'carmen'];
const user = { name: 'ben', canCode: true };
// We typically will JSON.stringify() the value before we set it...
localStorage.setItem('instructors', JSON.stringify(instructors));
localStorage.setItem('user', JSON.stringify(user));
// ...and JSON.parse() the value when we get it:
const storedInstructors = JSON.parse(localStorage.getItem('instructors'));
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log('storedInstructors:', storedInstructors);
console.log('storedUser:', storedUser);
When retrieving a value from localStorage, we use the JSON.parse() method which takes a string and tries to turn it into a value
localStorage Helpers
That's quite a bit of code to write and re-write every time we can to set or get values to/from localStorage.
To reduce repetition, we often write these two helper functions:
we control what the user of these functions can do (set, get, initialize, add, remove)
the caller of those exported functions doesn't directly interact with localStorage
the exported functions handle the interaction with localStorage
Sure, we can interact with localStorage outside of this file too but we should avoid that if we want to maintain the predictable and consistent behavior.
That file acts as a data layer. We might also decide to isolate our DOM manipulation code and create a DOM layer or create an event handling layer.
Using localStorage, we will build a data layer that is used to inform what is rendered, know as the view layer. When users interact with the view through the form, the data layer will be updated and we re-render the view.
This cycle of data > view > handle events > data looks like this: