6.7. Serializing and LocalStorage¶
Now we have a really well architected application. But it is still lacking one big feature. Persistence. Each time we bring up our web page, or even refresh the page, our list dissappears! That is bad and nobdy is going to buy our app if they have to start over from the beginning each time. What we need is a way to store the data. Our first step on the journey to persistence is to make use of the
localStorage of the browser. Before we dive into a new prototype we need to learn about two new concepts.
Here is an activecode example. The primary methods of the JSON object are
parse. The stringify method takes an object as a parameter and returns a JSON string.
Notice that there is nothing to import, the JSON object is always available for you to use.
Python is very similar, but the names of the methods are different. In python you call the
dumps method to serialize an object, and you call
loads to deserialize the string to an object.
Not everything can be serialized! For example, functions and methods cannot be serialized.
For custom objects, that is instances of classes that we create, the default behavior for JSON.stringify is to serialize the properties of the object but not the methods.
For example, take the Item class from our shopping list application. If we serialize this using
JSON.stringify we will get an object literal that contains the properties name, quantity, priority, store, section, etc. But none of the methods will be serialzed.
If we want our object to have some special behavior when we serialze it, we can write a method for our object called
toJSON The method takes no parameters and returns a string. Note that this string should be deserializable by the
6.7.2. Using the localStorage Object¶
Before HTML5 the only way to store data in the browser was in a cookie. That had a lot of limits in terms of size, and cookies are sent to the server with each request, so they were sent out into the internet over a potentially unsecure connection. In HTML5 localStorage was added to accomodate the needs to keep information persistent, and web storage objects were created.
There are two main web storage objects:
localStorage can hold at least 5MB of data with no expiration date.
sessionStorage stores data for one session – data is erased with the browser tab is closed.
The localStorage object has three important methods:
You can also access a key in localStorage directly using
Run the following example a few times.
Do you see anything wrong? Now reload the page and run it again. Notice that it keeps counting from where it left off.
Exercise Fix the counter so that it counts using the decimal number system.