Skip to content

Commit 77a8627

Browse files
feat(useIdbKeyval): ability to wait for IDB writes (#3338)
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
1 parent a0a6ff5 commit 77a8627

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

packages/integrations/useIDBKeyval/index.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ const flag = useIDBKeyval('my-flag', true) // returns Ref<boolean>
3030
// bind number
3131
const count = useIDBKeyval('my-count', 0) // returns Ref<number>
3232

33+
// awaiting IDB transaction
34+
await count.set(10)
35+
console.log('IDB transaction finished!')
36+
3337
// delete data from idb storage
3438
storedObject.value = null
3539
```

packages/integrations/useIDBKeyval/index.ts

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { ConfigurableFlush, MaybeRefOrGetter, RemovableRef } from '@vueuse/shared'
22
import { toValue } from '@vueuse/shared'
3+
import { watchPausable } from '@vueuse/core'
34
import type { Ref } from 'vue-demi'
4-
import { ref, shallowRef, watch } from 'vue-demi'
5+
import { ref, shallowRef } from 'vue-demi'
56
import { del, get, set, update } from 'idb-keyval'
67

78
export interface UseIDBOptions extends ConfigurableFlush {
@@ -31,7 +32,12 @@ export interface UseIDBOptions extends ConfigurableFlush {
3132
* @default true
3233
*/
3334
writeDefaults?: boolean
35+
}
3436

37+
export interface UseIDBKeyvalReturn<T> {
38+
data: RemovableRef<T>
39+
isFinished: Ref<boolean>
40+
set(value: T): Promise<void>
3541
}
3642

3743
/**
@@ -44,7 +50,7 @@ export function useIDBKeyval<T>(
4450
key: IDBValidKey,
4551
initialValue: MaybeRefOrGetter<T>,
4652
options: UseIDBOptions = {},
47-
): { data: RemovableRef<T>; isFinished: Ref<boolean> } {
53+
): UseIDBKeyvalReturn<T> {
4854
const {
4955
flush = 'pre',
5056
deep = true,
@@ -99,7 +105,21 @@ export function useIDBKeyval<T>(
99105
}
100106
}
101107

102-
watch(data, () => write(), { flush, deep })
108+
const {
109+
pause: pauseWatch,
110+
resume: resumeWatch,
111+
} = watchPausable(data, () => write(), { flush, deep })
103112

104-
return { isFinished, data: data as RemovableRef<T> }
113+
async function setData(value: T): Promise<void> {
114+
pauseWatch()
115+
data.value = value
116+
await write()
117+
resumeWatch()
118+
}
119+
120+
return {
121+
set: setData,
122+
isFinished,
123+
data: data as RemovableRef<T>,
124+
}
105125
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy