TIL
Today’s TIL is on a few browser storage methods I learned today!
1) LocalStorage - key-value pairs
-
you can store an array as a value, except you have to keep in mind that they are stored as STRINGS, so if you want to call the variable & utilize it as an array use JSON.parse() and store the array as JSON.stringify();
-
to store,
localStorage.setItem('key-name', value);
-
if you want to store Object or Array data types, remember to
JSON.stringify(data)
; -
to get item,
localStorage.getItem('key-name');
-
information is never cleared unless browser clear is b/c it’s running out of space, or if I clear it manually
2) Session Storage - key-value pairs
- very similar to LocalStorage but is ONLY stored as long as the page is open in the browser.
3) Cookies - attached to outgoing http requests as well
- which means that server needs to be prepared to use your cookies (or else there’s not a big point in
- you can also set an expiration date of the data stored in cookies.
document.cookie = '';
- this is adding something to the cookie (NOT clearing it or assigning a new value).
- setting something to cookies example:
const userId = 'u123';
document.cookie = `uid=${userId}`;
- this example stores ‘uid’ as name, and
u123
as value. - if you
console.log(document.cookie)
the result isuid=u123
; - if you have multiple key-value pairs stored in cookies, if you
console.log(document.cookies)
you will see ALL of them logged on the console with;
semicolons separating them. - if you want to store the expiration date there are a few options
example 1:
const userId = 'u123';
document.cookie = `uid=${userId}; max-age=2`;
- this example sets max-age which is in SECONDS.
example:
const userId = 'u123';
document.cookie = `uid=${userId}; expires=date-in-GMTString-format;