localStorage in Ionic 3

Multi-project and conflict-free usage of localStorage with a custom provider

Valentin Klinghammer
prototype.berlin

--

Problem

Instant preview in the Browser during development through ionic serve is one of the major upside for developers when using Ionic to build apps. But when you work on multiple apps and use localStorage to store things like access tokens and user data, things quickly become difficult to handle. Because during development ionic serves all apps from the same domain, localhost:8000 , there will be a conflict between multiple projects.

When you try to retrieve a localStorage key called accessToken in Project 2 has been previously set by Project 1, strange things will happen if you use it. This means

  • having to clear localStorage when working on multiple apps in parallel
  • having to clear the app anytime a user changes environments

This is inconvenient when switching between projects for quick fixes.

Solution

We will create a Provider that seamlessly uses a prefix for setting and getting localStorage keys. As an additional benefit, the Provider will also handle serialization and deserialization for storing and retrieving Objects.

The prefix will be project-specific as well as environment specific. We talked about A Simple Way to Use Environment Variables in Ionic 3 in a previous article.

Implementation

1. Generating a conflict-free localStorage key

To separate data for each project and each environment, we’ll use a combination of values as the actual localStorage key. So if you build Your Awesome App for the staging environment and want to save the key currentUser, what would be written into the localStorage would look like this: yourawesomeapp-stagingಠ_ಠcurrentUser.

As covered in the article mentioned above, we use a constants Provider, that would also hold our localStorage key. The relevant part looks like this.

2. The localStorage Service

First, let’s create a basic service that stores the reference to the global localStorage object.

Next, we create a set function that looks at the type of value parameter, automatically stringifying objects.

To set a value, use it as this.storageService.set('currentUser', { id: 1, name: 'Jo' }); after injecting it. This will set the key yourawesomeapp-stagingಠ_ಠcurrentUser.

Writing is just half of it, next we’ll write our reading method which will retrieve the key and parse them appropriately.

And that’s it. You can use it like this: this.storageService.get('currentUser'); to retrieve your data and even set a default value as a second parameter: this.storageService.get('currentUser', new User());

Here’s the whole Service for reference, including a delete method.

--

--