ionic-team / ionic-team/ionic-storage

service from documentation creates async bug at startup

Aperta
#229 7 commenti 42 reazioni 0 assegnatari Vedi su GitHub
Lingua principale
TypeScript
Stelle
456
Fork
97
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

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);
}
}
```

Guida per i contributori

Apri la guida per i contributori

Direzione di ricerca

Start with the Angular storage service example in README.md and compare its constructor initialization with the service shown in the issue. Update the documentation so early storage reads wait for initialization, then verify that the example no longer returns undefined when storage is accessed during app startup.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
angular, typescript
Ambito
documentation, mobile-dev
Tipo di issue
Bug
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.