ionic-team / ionic-team/ionic-storage

service from documentation creates async bug at startup

Open
#229 7 comments 42 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
456
Forks
97
PR merge metrics
No merged PRs in 30d

Description

From my testing of the [example service in the documentation](https://github.com/ionic-team/ionic-storage/blob/main/README.md#with-angular), it seems that it contains a bug.

The constructor calls `init()` without `async` (because it's not supported in a constructor):

```
constructor(private storage: Storage) {
this.init();
}
```

However, that means that if your app is relying on the storage very early on, you are going to get back `undefined` from a `get`.

For me, I have a tutorial guard set up which checks if the tutorial has been completed to decide if it should show the homepage or redirect to the tutorial slider page. It was always showing the tutorial because the result was `undefined`.

I've improved the service so that it takes a similar approach to the way that Ionic Storage is actually written; which is checking if the storage is initialised before trying to operate on it.

That way it can `await` the proper completion of the storage:

```
import { Injectable } from '@angular/core';

import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';

import { Storage } from '@ionic/storage-angular';

@Injectable({
providedIn: 'root'
})
export class StorageService {
private _storage: Storage | null = null;

constructor(private storage: Storage) {
}

async init() {
if(this._storage != null) {
return;
}
await this.storage.defineDriver(CordovaSQLiteDriver);
const storage = await this.storage.create();
this._storage = storage;
}

public async set(key: string, value: any): Promise {
await this.init();
return await this._storage?.set(key, value);
}

public async get(key: string): Promise {
await this.init();
return await this._storage?.get(key);
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.