Skip to content

Commit

Permalink
feat(useIdbKeyval): ability to wait for IDB writes (#3338)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
AbdallahAlhaddad and antfu committed Aug 25, 2023
1 parent a0a6ff5 commit 77a8627
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
4 changes: 4 additions & 0 deletions packages/integrations/useIDBKeyval/index.md
Expand Up @@ -30,6 +30,10 @@ const flag = useIDBKeyval('my-flag', true) // returns Ref<boolean>
// bind number
const count = useIDBKeyval('my-count', 0) // returns Ref<number>

// awaiting IDB transaction
await count.set(10)
console.log('IDB transaction finished!')

// delete data from idb storage
storedObject.value = null
```
28 changes: 24 additions & 4 deletions packages/integrations/useIDBKeyval/index.ts
@@ -1,7 +1,8 @@
import type { ConfigurableFlush, MaybeRefOrGetter, RemovableRef } from '@vueuse/shared'
import { toValue } from '@vueuse/shared'
import { watchPausable } from '@vueuse/core'
import type { Ref } from 'vue-demi'
import { ref, shallowRef, watch } from 'vue-demi'
import { ref, shallowRef } from 'vue-demi'
import { del, get, set, update } from 'idb-keyval'

export interface UseIDBOptions extends ConfigurableFlush {
Expand Down Expand Up @@ -31,7 +32,12 @@ export interface UseIDBOptions extends ConfigurableFlush {
* @default true
*/
writeDefaults?: boolean
}

export interface UseIDBKeyvalReturn<T> {
data: RemovableRef<T>
isFinished: Ref<boolean>
set(value: T): Promise<void>
}

/**
Expand All @@ -44,7 +50,7 @@ export function useIDBKeyval<T>(
key: IDBValidKey,
initialValue: MaybeRefOrGetter<T>,
options: UseIDBOptions = {},
): { data: RemovableRef<T>; isFinished: Ref<boolean> } {
): UseIDBKeyvalReturn<T> {
const {
flush = 'pre',
deep = true,
Expand Down Expand Up @@ -99,7 +105,21 @@ export function useIDBKeyval<T>(
}
}

watch(data, () => write(), { flush, deep })
const {
pause: pauseWatch,
resume: resumeWatch,
} = watchPausable(data, () => write(), { flush, deep })

return { isFinished, data: data as RemovableRef<T> }
async function setData(value: T): Promise<void> {
pauseWatch()
data.value = value
await write()
resumeWatch()
}

return {
set: setData,
isFinished,
data: data as RemovableRef<T>,
}
}

0 comments on commit 77a8627

Please sign in to comment.