Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useIdbKeyval): ability to wait for IDB writes #3338

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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>,
}
}