Skip to content

Commit 3cca016

Browse files
committed
PWA: add support for awaiting the readiness of the store.
1 parent 3b4933a commit 3cca016

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

pwa/src/store.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@ class Store {
99
idb: IDBDatabase | null = null;
1010
state: State = new State();
1111

12+
ready: Promise<void>;
13+
private resolveReady!: () => void;
14+
15+
constructor() {
16+
this.ready = new Promise<void>((resolve) => {
17+
this.resolveReady = resolve;
18+
});
19+
}
20+
1221
async init() {
1322
this.idb = await this.openIndexedBD();
1423

@@ -51,14 +60,23 @@ class Store {
5160
.transaction(OBJECT_STORE_NAME, "readonly")
5261
.objectStore(OBJECT_STORE_NAME);
5362

63+
let pending = 0;
64+
5465
for (const [ref, property] of this.state) {
66+
pending++;
67+
5568
objectStore.get(property).onsuccess = (event) => {
5669
const value: unknown = (event.target as IDBRequest).result;
5770
if (value !== undefined && typeof value === typeof ref.value) {
5871
ref.value = value as typeof ref.value;
59-
return;
72+
} else {
73+
this.put(ref.value, property);
74+
}
75+
76+
pending--;
77+
if (pending === 0) {
78+
this.resolveReady();
6079
}
61-
this.put(ref.value, property);
6280
};
6381
}
6482

@@ -68,7 +86,7 @@ class Store {
6886
}
6987
}
7088

71-
const store = new Store();
72-
await store.init();
89+
export const store = new Store();
90+
void store.init();
7391

7492
export const state = store.state;

0 commit comments

Comments
 (0)