Skip to content

useRTDB

Category
Export Size
218 B
Package
@reause/firebase
Last Changed
5 days ago

Reactive Firebase Realtime Database binding. Making it straightforward to always keep your local data in sync with remotes databases.

Usage

tsx
import { 
useRTDB
} from '@reause/firebase'
import {
initializeApp
} from 'firebase/app'
import {
getDatabase
,
ref
} from 'firebase/database'
const
app
=
initializeApp
({ /* config */ })
const
db
=
getDatabase
(
app
)
const [
todos
,
setTodos
] =
useRTDB
<
Record
<string,
Todo
>>(
ref
(
db
, 'todos'))

Options

OptionTypeDefaultDescription
autoDisposebooleantrueAutomatically unsubscribe when the component is unmounted
errorHandler(err: Error) => voidconsole.errorCustom error handler for database errors

Return Value

Returns a T | undefined value that is automatically updated when the database value changes.

Reusing Database References

You can reuse the db reference by passing autoDispose: false:

tsx
const [
todos
] =
useRTDB
(ref(db, 'todos'), {
autoDispose
: false })

or share one subscription between components with createSharedHook from the shared package — the port of createSharedComposable. (Upstream's page recommends createGlobalState, but reause's createGlobalState mirrors react-use: its initial state is resolved at module scope, so it cannot host a hook.)

ts
// store.ts
import { 
useRTDB
} from '@reause/firebase'
import {
createSharedHook
} from '@reause/shared'
import {
ref
} from 'firebase/database'
export const
useTodos
=
createSharedHook
(
() =>
useRTDB
(
ref
(db, 'todos')),
)

Type Declarations

ts
export interface UseRTDBOptions {
    errorHandler?: (err: Error) => void;
    autoDispose?: boolean;
}

export type UseRTDBReturn<T> = [
    data: T | undefined,
    setData: (value: T | undefined) => void
]

export function useRTDB<T = any>(docRef: DatabaseReference, options?: UseRTDBOptions): UseRTDBReturn<T>

Source

Source · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
39ed3 - feat(firebase): add useRTDB (#201)

Released under the MIT License. v0.1.8