Tip 46: Maintain State Over Time with LocalStorage
Preserving user data
An obvious solution is to create a login. The problem is that many users will abandon a site if they’re forced to log in. A better, albeit imperfect, solution is to store data locally. When you save data locally, you can preserve information on a particular browser on a particular device.
Of course, everyone uses multiple devices. So saving data to a browser won’t help a user who works across multiple devices. Still, it’s far less intrusive than demanding a user make yet another account.
localStorge to store user data
You can easily save user information with
Think back to your pet adoption site from Tip 13, Update Key-Value Data Clearly with Maps. You set up a series of filters to show only relevant pets. Because pet owners tend to prefer certain types of animals—lovers of labradors probably won’t look for tiny dogs—you could do them a favor if you save their searches between sessions.
Start by saving a
breed preference. To save a
breed, you just need to set the
value on the
localStorage object using the
setItem() method. You pass the key
as the first argument and the value as the second. The syntax should look
familiar. It’s nearly identical to the method for setting data on a