The Storage API Module #38 Flashcards
What are the two mechanisms provided by the Web Storage API.
“Session Storage” and “Local Storage”.
How does session storage work?
This data only exists as long as the user is on a page. As soon as the tab or window is closed the data is cleared. Multiple pages of the same site will have unique instances of session storage data.
How does Local Storage differ from Session Storage
While Session Storage is cleared immediately upon the closure of a browser window, Local Storage persists until it is explicitly removed by the program or the end user.
How does their set of properties and methods differ?
They do not differ. They access the same Storage object.
What property is available to the Storage object?
Length (which is the number of data items stored into it)
Describe the setItem method
Adds the item to the storage and accepts a string as a key and a string as a value. As below:
localStorage.setItem(“username”, “flaviocopes”)
localStorage.setItem(“id”, “123”)
What happens if you pass a value in setItem that is not a string?
Boom, the item is converted into string format. Consider the below:
localStorage.setItem(“test”, 123) // stored as ‘123’ or
localStorage.setItem(“test”, {test: 1}) stored as “[object Object]”
How can we retrieve a key value from storage?
By invoking the getItem(key) syntax. Just use the name of the key inside the parenthesis to retrieve the value.
localStorage.getItem(“username”) // ‘flaviocopes’
localStorage.getItem(“id”) // ‘123’
How can an item be removed from the storage object?
By invoking the (removeItem(key) method.
localStorage.removeItem(“id”)
When you encounter key(n) or key number what is the concept here?
Keys added into the Storage Object have index numbers. However MDN states that the index is set by the user agent (browser) therefore the order is unreliable. Storage items that do not exist return a value of NULL.
How can we clear the storage object.
By calling the clear( ) method. As below:
localStorage.clear( )
What are the storage limits of Local and Session storage?
Your mileage my vary. It seems to me that >5mb is sufficient. That said, for the big market share browsers, such as Chrome, Firefox and IE allow for 10mb while Safari allows 5mb of Local Storage and unlimited Session Storage. Same on mobile, unless you’re targeting very old versions of iOS.
How are errors handled when the storage quota gets exceeded?
Using the exact same structure (try & catch) as error handling for Fetch or Axios. See below:
try { localStorage.setItem("key", "value") } catch (domException) { if ( ["QuotaExceededError", "NS_ERROR_DOM_QUOTA_REACHED"].includes( domException.name ) ) { // handle quota limit exceeded error } }