Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useFirestore.md
1---2category: '@Firebase'3---45# useFirestore67Reactive [Firestore](https://firebase.google.com/docs/firestore) binding. Making it straightforward to **always keep your local data in sync** with remotes databases.89## Usage1011```ts {9,12,17,22}12import { useFirestore } from '@vueuse/firebase/useFirestore'13import { initializeApp } from 'firebase/app'14import { collection, doc, getFirestore, limit, orderBy, query } from 'firebase/firestore'15import { computed, shallowRef } from 'vue'1617const app = initializeApp({ projectId: 'MY PROJECT ID' })18const db = getFirestore(app)1920const todos = useFirestore(collection(db, 'todos'))2122// or for doc reference23const user = useFirestore(doc(db, 'users', 'my-user-id'))2425// you can also use ref value for reactive query26const postsLimit = shallowRef(10)27const postsQuery = computed(() => query(collection(db, 'posts'), orderBy('createdAt', 'desc'), limit(postsLimit.value)))28const posts = useFirestore(postsQuery)2930// you can use the boolean value to tell a query when it is ready to run31// when it gets falsy value, return the initial value32const userId = shallowRef('')33const userQuery = computed(() => userId.value && doc(db, 'users', userId.value))34const userData = useFirestore(userQuery, null)35```3637### Return Value3839- For **Document Reference**: Returns `Ref<T | null>` (single document with `id` property)40- For **Query**: Returns `Ref<T[]>` (array of documents, each with `id` property)4142The document `id` is automatically added as a read-only property to each returned document.4344### Options4546| Option | Type | Default | Description |47| -------------- | ---------------------- | --------------- | -------------------------------------------------------------------------- |48| `errorHandler` | `(err: Error) => void` | `console.error` | Custom error handler |49| `autoDispose` | `boolean \| number` | `true` | Auto-unsubscribe on scope dispose. Pass a number for delayed dispose (ms). |5051### Error Handling5253```ts54const todos = useFirestore(collection(db, 'todos'), [], {55errorHandler: (err) => {56console.error('Firestore error:', err)57// Handle error (e.g., show notification)58},59})60```6162## Share across instances6364You can reuse the db reference by passing `autoDispose: false`. You can also set an amount of milliseconds before auto disposing the db reference.6566Note : Getting a not disposed db reference again don't cost a Firestore read.6768```ts69import { useFirestore } from '@vueuse/firebase/useFirestore'70import { collection } from 'firebase/firestore'71// ---cut---72const todos = useFirestore(collection(db, 'todos'), undefined, { autoDispose: false })73```7475or use `createGlobalState` from the core package7677```ts twoslash include store78// @filename: store.ts79// ---cut---80// store.ts81import { createGlobalState } from '@vueuse/core'82import { useFirestore } from '@vueuse/firebase/useFirestore'8384export const useTodos = createGlobalState(85() => useFirestore(collection(db, 'todos')),86)87```8889```vue90<!-- app.vue -->91<script setup lang="ts">92// @include: store93// ---cut---94import { useTodos } from './store'9596const todos = useTodos()97</script>98```99100## Type Declarations101102```ts103export interface UseFirestoreOptions {104errorHandler?: (err: Error) => void105autoDispose?: boolean | number106}107export type FirebaseDocRef<T> = Query<T> | DocumentReference<T>108type Falsy = false | 0 | "" | null | undefined109export declare function useFirestore<T extends DocumentData>(110maybeDocRef: MaybeRef<DocumentReference<T> | Falsy>,111initialValue: T,112options?: UseFirestoreOptions,113): Ref<T | null>114export declare function useFirestore<T extends DocumentData>(115maybeDocRef: MaybeRef<Query<T> | Falsy>,116initialValue: T[],117options?: UseFirestoreOptions,118): Ref<T[]>119export declare function useFirestore<T extends DocumentData>(120maybeDocRef: MaybeRef<DocumentReference<T> | Falsy>,121initialValue?: T | undefined | null,122options?: UseFirestoreOptions,123): Ref<T | undefined | null>124export declare function useFirestore<T extends DocumentData>(125maybeDocRef: MaybeRef<Query<T> | Falsy>,126initialValue?: T[],127options?: UseFirestoreOptions,128): Ref<T[] | undefined>129```130