@firebase/database
- Version 1.0.9
- Published
- 8.82 MB
- 7 dependencies
- Apache-2.0 license
Install
npm i @firebase/database
yarn add @firebase/database
pnpm add @firebase/database
Overview
Firebase Realtime Database
Index
Functions
- child()
- connectDatabaseEmulator()
- enableLogging()
- endAt()
- endBefore()
- equalTo()
- forceLongPolling()
- forceWebSockets()
- get()
- getDatabase()
- goOffline()
- goOnline()
- increment()
- limitToFirst()
- limitToLast()
- off()
- onChildAdded()
- onChildChanged()
- onChildMoved()
- onChildRemoved()
- onDisconnect()
- onValue()
- orderByChild()
- orderByKey()
- orderByPriority()
- orderByValue()
- push()
- query()
- ref()
- refFromURL()
- remove()
- runTransaction()
- serverTimestamp()
- set()
- setPriority()
- setWithPriority()
- startAfter()
- startAt()
- update()
Classes
Interfaces
Type Aliases
Functions
function child
child: (parent: DatabaseReference, path: string) => DatabaseReference;
Gets a
Reference
for the location at the specified relative path.The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first").
Parameter parent
The parent location.
Parameter path
A relative path from this location to the desired child location.
Returns
The specified child location.
function connectDatabaseEmulator
connectDatabaseEmulator: ( db: Database, host: string, port: number, options?: { mockUserToken?: EmulatorMockTokenOptions | string }) => void;
Modify the provided instance to communicate with the Realtime Database emulator.
Note: This method must be called before performing any other operation.
Parameter db
The instance to modify.
Parameter host
The emulator host (ex: localhost)
Parameter port
The emulator port (ex: 8080)
Parameter
options.mockUserToken - the mock auth token to use for unit testing Security Rules
function enableLogging
enableLogging: { (enabled: boolean, persistent?: boolean): any; (logger: (message: string) => unknown): any;};
Logs debugging information to the console.
Parameter enabled
Enables logging if
true
, disables logging iffalse
.Parameter persistent
Remembers the logging state between page refreshes if
true
.Logs debugging information to the console.
Parameter logger
A custom logger function to control how things get logged.
function endAt
endAt: ( value: number | string | boolean | null, key?: string) => QueryConstraint;
Creates a
QueryConstraint
with the specified ending point.Using
startAt()
,startAfter()
,endBefore()
,endAt()
andequalTo()
allows you to choose arbitrary starting and ending points for your queries.The ending point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name less than or equal to the specified key.
You can read more about
endAt()
in Filtering data.Parameter value
The value to end at. The argument type depends on which
orderBy*()
function was used in this query. Specify a value that matches theorderBy*()
type. When used in combination withorderByKey()
, the value must be a string.Parameter key
The child key to end at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.
function endBefore
endBefore: ( value: number | string | boolean | null, key?: string) => QueryConstraint;
Creates a
QueryConstraint
with the specified ending point (exclusive).Using
startAt()
,startAfter()
,endBefore()
,endAt()
andequalTo()
allows you to choose arbitrary starting and ending points for your queries.The ending point is exclusive. If only a value is provided, children with a value less than the specified value will be included in the query. If a key is specified, then children must have a value less than or equal to the specified value and a key name less than the specified key.
Parameter value
The value to end before. The argument type depends on which
orderBy*()
function was used in this query. Specify a value that matches theorderBy*()
type. When used in combination withorderByKey()
, the value must be a string.Parameter key
The child key to end before, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.
function equalTo
equalTo: ( value: number | string | boolean | null, key?: string) => QueryConstraint;
Creates a
QueryConstraint
that includes children that match the specified value.Using
startAt()
,startAfter()
,endBefore()
,endAt()
andequalTo()
allows you to choose arbitrary starting and ending points for your queries.The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have exactly the specified key as their key name. This can be used to filter result sets with many matches for the same value.
You can read more about
equalTo()
in Filtering data.Parameter value
The value to match for. The argument type depends on which
orderBy*()
function was used in this query. Specify a value that matches theorderBy*()
type. When used in combination withorderByKey()
, the value must be a string.Parameter key
The child key to start at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.
function forceLongPolling
forceLongPolling: () => void;
Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
function forceWebSockets
forceWebSockets: () => void;
Force the use of websockets instead of longPolling.
function get
get: (query: Query) => Promise<DataSnapshot>;
Gets the most up-to-date result for this query.
Parameter query
The query to run.
Returns
A
Promise
which resolves to the resulting DataSnapshot if a value is available, or rejects if the client is unable to return a value (e.g., if the server is unreachable and there is nothing cached).
function getDatabase
getDatabase: (app?: FirebaseApp, url?: string) => Database;
Returns the instance of the Realtime Database SDK that is associated with the provided @firebase/app#FirebaseApp. Initializes a new instance with default settings if no instance exists or if the existing instance uses a custom database URL.
Parameter app
The @firebase/app#FirebaseApp instance that the returned Realtime Database instance is associated with.
Parameter url
The URL of the Realtime Database instance to connect to. If not provided, the SDK connects to the default instance of the Firebase App.
Returns
The
Database
instance of the provided app.
function goOffline
goOffline: (db: Database) => void;
Disconnects from the server (all Database operations will be completed offline).
The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, the
goOffline()
andgoOnline()
methods may be used to control the client connection in cases where a persistent connection is undesirable.While offline, the client will no longer receive data updates from the Database. However, all Database operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Database server.
To reconnect to the Database and begin receiving remote events, see
goOnline()
.Parameter db
The instance to disconnect.
function goOnline
goOnline: (db: Database) => void;
Reconnects to the server and synchronizes the offline Database state with the server state.
This method should be used after disabling the active connection with
goOffline()
. Once reconnected, the client will transmit the proper data and fire the appropriate events so that your client "catches up" automatically.Parameter db
The instance to reconnect.
function increment
increment: (delta: number) => object;
Returns a placeholder value that can be used to atomically increment the current database value by the provided delta.
Parameter delta
the amount to modify the current value atomically.
Returns
A placeholder value for modifying data atomically server-side.
function limitToFirst
limitToFirst: (limit: number) => QueryConstraint;
Creates a new
QueryConstraint
that if limited to the first specific number of children.The
limitToFirst()
method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added
events. If we have fewer than 100 messages stored in our Database, achild_added
event will fire for each message. However, if we have over 100 messages, we will only receive achild_added
event for the first 100 ordered messages. As items change, we will receivechild_removed
events for each item that drops out of the active list so that the total number stays at 100.You can read more about
limitToFirst()
in Filtering data.Parameter limit
The maximum number of nodes to include in this query.
function limitToLast
limitToLast: (limit: number) => QueryConstraint;
Creates a new
QueryConstraint
that is limited to return only the last specified number of children.The
limitToLast()
method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100child_added
events. If we have fewer than 100 messages stored in our Database, achild_added
event will fire for each message. However, if we have over 100 messages, we will only receive achild_added
event for the last 100 ordered messages. As items change, we will receivechild_removed
events for each item that drops out of the active list so that the total number stays at 100.You can read more about
limitToLast()
in Filtering data.Parameter limit
The maximum number of nodes to include in this query.
function off
off: ( query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown) => void;
Detaches a callback previously attached with the corresponding
on*()
(onValue
,onChildAdded
) listener. Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from the respectiveon*
callbacks.Detach a callback previously attached with
on*()
. Callingoff()
on a parent listener will not automatically remove listeners registered on child nodes,off()
must also be called on any child listeners to remove the callback.If a callback is not specified, all callbacks for the specified eventType will be removed. Similarly, if no eventType is specified, all callbacks for the
Reference
will be removed.Individual listeners can also be removed by invoking their unsubscribe callbacks.
Parameter query
The query that the listener was registered with.
Parameter eventType
One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved." If omitted, all callbacks for the
Reference
will be removed.Parameter callback
The callback function that was passed to
on()
orundefined
to remove all callbacks.
function onChildAdded
onChildAdded: { ( query: Query, callback: ( snapshot: DataSnapshot, previousChildName?: string | null ) => unknown, cancelCallback?: (error: Error) => unknown ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, options: ListenOptions ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions ): Unsubscribe;};
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildAdded
event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot
passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildAdded
event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot
passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildAdded
event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. TheDataSnapshot
passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
function onChildChanged
onChildChanged: { ( query: Query, callback: ( snapshot: DataSnapshot, previousChildName: string | null ) => unknown, cancelCallback?: (error: Error) => unknown ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, options: ListenOptions ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions ): Unsubscribe;};
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildChanged
event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed
event may represent multiple changes to the child. TheDataSnapshot
passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildChanged
event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed
event may represent multiple changes to the child. TheDataSnapshot
passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildChanged
event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a singlechild_changed
event may represent multiple changes to the child. TheDataSnapshot
passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
function onChildMoved
onChildMoved: { ( query: Query, callback: ( snapshot: DataSnapshot, previousChildName: string | null ) => unknown, cancelCallback?: (error: Error) => unknown ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, options: ListenOptions ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot, previousChildName: string) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions ): Unsubscribe;};
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildMoved
event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot
passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildMoved
event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot
passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildMoved
event will be triggered when a child's sort order changes such that its position relative to its siblings changes. TheDataSnapshot
passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, ornull
if it is the first child.Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
function onChildRemoved
onChildRemoved: { ( query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions ): Unsubscribe;};
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildRemoved
event will be triggered once every time a child is removed. TheDataSnapshot
passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly calls
remove()
on that child or one of its ancestors - a client callsset(null)
on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildRemoved
event will be triggered once every time a child is removed. TheDataSnapshot
passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly calls
remove()
on that child or one of its ancestors - a client callsset(null)
on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onChildRemoved
event will be triggered once every time a child is removed. TheDataSnapshot
passed into the callback will be the old data for the child that was removed. A child will get removed when either:- a client explicitly calls
remove()
on that child or one of its ancestors - a client callsset(null)
on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or
null
if it is the first child.Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
function onDisconnect
onDisconnect: (ref: DatabaseReference) => OnDisconnect;
Returns an
OnDisconnect
object - see Enabling Offline Capabilities in JavaScript for more information on how to use it.Parameter ref
The reference to add OnDisconnect triggers for.
function onValue
onValue: { ( query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions ): Unsubscribe; ( query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions ): Unsubscribe;};
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onValue
event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot
passed to the callback will be for the location at whichon()
was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot
(val()
will returnnull
).Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onValue
event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot
passed to the callback will be for the location at whichon()
was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot
(val()
will returnnull
).Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
Listens for data changes at a particular location.
This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.
An
onValue
event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. TheDataSnapshot
passed to the callback will be for the location at whichon()
was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an emptyDataSnapshot
(val()
will returnnull
).Parameter query
The query to run.
Parameter callback
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
Parameter cancelCallback
An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an
Error
object indicating why the failure occurred.Parameter options
An object that can be used to configure
onlyOnce
, which then removes the listener after its first invocation.Returns
A function that can be invoked to remove the listener.
function orderByChild
orderByChild: (path: string) => QueryConstraint;
Creates a new
QueryConstraint
that orders by the specified child key.Queries can only order by one key at a time. Calling
orderByChild()
multiple times on the same query is an error.Firebase queries allow you to order your data by any child key on the fly. However, if you know in advance what your indexes will be, you can define them via the .indexOn rule in your Security Rules for better performance. See thehttps://firebase.google.com/docs/database/security/indexing-data rule for more information.
You can read more about
orderByChild()
in Sort data.Parameter path
The path to order by.
function orderByKey
orderByKey: () => QueryConstraint;
Creates a new
QueryConstraint
that orders by the key.Sorts the results of a query by their (ascending) key values.
You can read more about
orderByKey()
in Sort data.
function orderByPriority
orderByPriority: () => QueryConstraint;
Creates a new
QueryConstraint
that orders by priority.Applications need not use priority but can order collections by ordinary properties (see Sort data for alternatives to priority.
function orderByValue
orderByValue: () => QueryConstraint;
Creates a new
QueryConstraint
that orders by value.If the children of a query are all scalar values (string, number, or boolean), you can order the results by their (ascending) values.
You can read more about
orderByValue()
in Sort data.
function push
push: (parent: DatabaseReference, value?: unknown) => ThenableReference;
Generates a new child location using a unique key and returns its
Reference
.This is the most common pattern for adding data to a collection of items.
If you provide a value to
push()
, the value is written to the generated location. If you don't pass a value, nothing is written to the database and the child remains empty (but you can use theReference
elsewhere).The unique keys generated by
push()
are ordered by the current time, so the resulting list of items is chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).See Append to a list of data. See The 2^120 Ways to Ensure Unique Identifiers.
Parameter parent
The parent location.
Parameter value
Optional value to be written at the generated location.
Returns
Combined
Promise
andReference
; resolves when write is complete, but can be used immediately as theReference
to the child location.
function query
query: (query: Query, ...queryConstraints: QueryConstraint[]) => Query;
Creates a new immutable instance of
Query
that is extended to also include additional query constraints.Parameter query
The Query instance to use as a base for the new constraints.
Parameter queryConstraints
The list of
QueryConstraint
s to apply.Throws
if any of the provided query constraints cannot be combined with the existing or new constraints.
function ref
ref: (db: Database, path?: string) => DatabaseReference;
Returns a
Reference
representing the location in the Database corresponding to the provided path. If no path is provided, theReference
will point to the root of the Database.Parameter db
The database instance to obtain a reference for.
Parameter path
Optional path representing the location the returned
Reference
will point. If not provided, the returnedReference
will point to the root of the Database.Returns
If a path is provided, a
Reference
pointing to the provided path. Otherwise, aReference
pointing to the root of the Database.
function refFromURL
refFromURL: (db: Database, url: string) => DatabaseReference;
Returns a
Reference
representing the location in the Database corresponding to the provided Firebase URL.An exception is thrown if the URL is not a valid Firebase Database URL or it has a different domain than the current
Database
instance.Note that all query parameters (
orderBy
,limitToLast
, etc.) are ignored and are not applied to the returnedReference
.Parameter db
The database instance to obtain a reference for.
Parameter url
The Firebase URL at which the returned
Reference
will point.Returns
A
Reference
pointing to the provided Firebase URL.
function remove
remove: (ref: DatabaseReference) => Promise<void>;
Removes the data at this Database location.
Any data at child locations will also be deleted.
The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.
Parameter ref
The location to remove.
Returns
Resolves when remove on server is complete.
function runTransaction
runTransaction: ( ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions) => Promise<TransactionResult>;
Atomically modifies the data at this location.
Atomically modify the data at this location. Unlike a normal
set()
, which just overwrites the data regardless of its previous value,runTransaction()
is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.To accomplish this, you pass
runTransaction()
an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.Note: Modifying data with
set()
will cancel any pending transactions at that location, so extreme care should be taken if mixingset()
andrunTransaction()
to update the same data.Note: When using transactions with Security and Firebase Rules in place, be aware that a client needs
.read
access in addition to.write
access in order to perform a transaction. This is because the client-side nature of transactions requires the client to read the data in order to transactionally update it.Parameter ref
The location to atomically modify.
Parameter transactionUpdate
A developer-supplied function which will be passed the current data stored at this location (as a JavaScript object). The function should return the new value it would like written (as a JavaScript object). If
undefined
is returned (i.e. you return with no arguments) the transaction will be aborted and the data at this location will not be modified.Parameter options
An options object to configure transactions.
Returns
A
Promise
that can optionally be used instead of theonComplete
callback to handle success and failure.
function serverTimestamp
serverTimestamp: () => object;
Returns a placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.
function set
set: (ref: DatabaseReference, value: unknown) => Promise<void>;
Writes data to this Database location.
This will overwrite any data at this location and all child locations.
The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the
onComplete
callback will be called asynchronously after synchronization has finished.Passing
null
for the new value is equivalent to callingremove()
; namely, all data at this location and all child locations will be deleted.set()
will remove any priority stored at this location, so if priority is meant to be preserved, you need to usesetWithPriority()
instead.Note that modifying data with
set()
will cancel any pending transactions at that location, so extreme care should be taken if mixingset()
andtransaction()
to modify the same data.A single
set()
will generate a single "value" event at the location where theset()
was performed.Parameter ref
The location to write to.
Parameter value
The value to be written (string, number, boolean, object, array, or null).
Returns
Resolves when write to server is complete.
function setPriority
setPriority: ( ref: DatabaseReference, priority: string | number | null) => Promise<void>;
Sets a priority for the data at this Database location.
Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data ).
Parameter ref
The location to write to.
Parameter priority
The priority to be written (string, number, or null).
Returns
Resolves when write to server is complete.
function setWithPriority
setWithPriority: ( ref: DatabaseReference, value: unknown, priority: string | number | null) => Promise<void>;
Writes data the Database location. Like
set()
but also specifies the priority for that data.Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data ).
Parameter ref
The location to write to.
Parameter value
The value to be written (string, number, boolean, object, array, or null).
Parameter priority
The priority to be written (string, number, or null).
Returns
Resolves when write to server is complete.
function startAfter
startAfter: ( value: number | string | boolean | null, key?: string) => QueryConstraint;
Creates a
QueryConstraint
with the specified starting point (exclusive).Using
startAt()
,startAfter()
,endBefore()
,endAt()
andequalTo()
allows you to choose arbitrary starting and ending points for your queries.The starting point is exclusive. If only a value is provided, children with a value greater than the specified value will be included in the query. If a key is specified, then children must have a value greater than or equal to the specified value and a a key name greater than the specified key.
Parameter value
The value to start after. The argument type depends on which
orderBy*()
function was used in this query. Specify a value that matches theorderBy*()
type. When used in combination withorderByKey()
, the value must be a string.Parameter key
The child key to start after. This argument is only allowed if ordering by child, value, or priority.
function startAt
startAt: ( value?: number | string | boolean | null, key?: string) => QueryConstraint;
Creates a
QueryConstraint
with the specified starting point.Using
startAt()
,startAfter()
,endBefore()
,endAt()
andequalTo()
allows you to choose arbitrary starting and ending points for your queries.The starting point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name greater than or equal to the specified key.
You can read more about
startAt()
in Filtering data.Parameter value
The value to start at. The argument type depends on which
orderBy*()
function was used in this query. Specify a value that matches theorderBy*()
type. When used in combination withorderByKey()
, the value must be a string.Parameter key
The child key to start at. This argument is only allowed if ordering by child, value, or priority.
function update
update: (ref: DatabaseReference, values: object) => Promise<void>;
Writes multiple values to the Database at once.
The
values
argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.As opposed to the
set()
method,update()
can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the
onComplete
callback will be called asynchronously after synchronization has finished.A single
update()
will generate a single "value" event at the location where theupdate()
was performed, regardless of how many children were modified.Note that modifying data with
update()
will cancel any pending transactions at that location, so extreme care should be taken if mixingupdate()
andtransaction()
to modify the same data.Passing
null
toupdate()
will remove the data at this location.Parameter ref
The location to write to.
Parameter values
Object containing multiple values.
Returns
Resolves when update on server is complete.
Classes
class Database
class Database {}
Class representing a Firebase Realtime Database.
property 'type'
readonly 'type': string;
Represents a
Database
instance.
property app
readonly app: FirebaseApp;
The @firebase/app#FirebaseApp associated with this Realtime Database instance.
class DataSnapshot
class DataSnapshot {}
A
DataSnapshot
contains data from a Database location.Any time you read data from the Database, you receive the data as a
DataSnapshot
. ADataSnapshot
is passed to the event callbacks you attach withon()
oronce()
. You can extract the contents of the snapshot as a JavaScript object by calling theval()
method. Alternatively, you can traverse into the snapshot by callingchild()
to return child snapshots (which you could then callval()
on).A
DataSnapshot
is an efficiently generated, immutable copy of the data at a Database location. It cannot be modified and will never change (to modify data, you always call theset()
method on aReference
directly).
property key
readonly key: string;
The key (last part of the path) of the location of this
DataSnapshot
.The last token in a Database location is considered its key. For example, "ada" is the key for the /users/ada/ node. Accessing the key on any
DataSnapshot
will return the key for the location that generated it. However, accessing the key on the root URL of a Database will returnnull
.
property priority
readonly priority: string | number;
Gets the priority value of the data in this
DataSnapshot
.Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data ).
property ref
readonly ref: DatabaseReference;
The location of this DataSnapshot.
property size
readonly size: number;
Returns the number of child properties of this
DataSnapshot
.
method child
child: (path: string) => DataSnapshot;
Gets another
DataSnapshot
for the location at the specified relative path.Passing a relative path to the
child()
method of a DataSnapshot returns anotherDataSnapshot
for the location at the specified relative path. The relative path can either be a simple child name (for example, "ada") or a deeper, slash-separated path (for example, "ada/name/first"). If the child location has no data, an emptyDataSnapshot
(that is, aDataSnapshot
whose value isnull
) is returned.Parameter path
A relative path to the location of child data.
method exists
exists: () => boolean;
Returns true if this
DataSnapshot
contains any data. It is slightly more efficient than usingsnapshot.val() !== null
.
method exportVal
exportVal: () => any;
Exports the entire contents of the DataSnapshot as a JavaScript object.
The
exportVal()
method is similar toval()
, except priority information is included (if available), making it suitable for backing up your data.Returns
The DataSnapshot's contents as a JavaScript value (Object, Array, string, number, boolean, or
null
).
method forEach
forEach: (action: (child: IteratedDataSnapshot) => boolean | void) => boolean;
Enumerates the top-level children in the
IteratedDataSnapshot
.Because of the way JavaScript objects work, the ordering of data in the JavaScript object returned by
val()
is not guaranteed to match the ordering on the server nor the ordering ofonChildAdded()
events. That is whereforEach()
comes in handy. It guarantees the children of aDataSnapshot
will be iterated in their query order.If no explicit
orderBy*()
method is used, results are returned ordered by key (unless priorities are used, in which case, results are returned by priority).Parameter action
A function that will be called for each child DataSnapshot. The callback can return true to cancel further enumeration.
Returns
true if enumeration was canceled due to your callback returning true.
method hasChild
hasChild: (path: string) => boolean;
Returns true if the specified child path has (non-null) data.
Parameter path
A relative path to the location of a potential child.
Returns
true
if data exists at the specified child path; elsefalse
.
method hasChildren
hasChildren: () => boolean;
Returns whether or not the
DataSnapshot
has any non-null
child properties.You can use
hasChildren()
to determine if aDataSnapshot
has any children. If it does, you can enumerate them usingforEach()
. If it doesn't, then either this snapshot contains a primitive value (which can be retrieved withval()
) or it is empty (in which case,val()
will returnnull
).Returns
true if this snapshot has any children; else false.
method toJSON
toJSON: () => object | null;
Returns a JSON-serializable representation of this object.
method val
val: () => any;
Extracts a JavaScript value from a
DataSnapshot
.Depending on the data in a
DataSnapshot
, theval()
method may return a scalar type (string, number, or boolean), an array, or an object. It may also return null, indicating that theDataSnapshot
is empty (contains no data).Returns
The DataSnapshot's contents as a JavaScript value (Object, Array, string, number, boolean, or
null
).
class OnDisconnect
class OnDisconnect {}
The
onDisconnect
class allows you to write or clear data when your client disconnects from the Database server. These updates occur whether your client disconnects cleanly or not, so you can rely on them to clean up data even if a connection is dropped or a client crashes.The
onDisconnect
class is most commonly used to manage presence in applications where it is useful to detect how many clients are connected and when other clients disconnect. See Enabling Offline Capabilities in JavaScript for more information.To avoid problems when a connection is dropped before the requests can be transferred to the Database server, these functions should be called before writing any data.
Note that
onDisconnect
operations are only triggered once. If you want an operation to occur each time a disconnect occurs, you'll need to re-establish theonDisconnect
operations each time you reconnect.
method cancel
cancel: () => Promise<void>;
Cancels all previously queued
onDisconnect()
set or update events for this location and all children.If a write has been queued for this location via a
set()
orupdate()
at a parent location, the write at this location will be canceled, though writes to sibling locations will still occur.Returns
Resolves when synchronization to the server is complete.
method remove
remove: () => Promise<void>;
Ensures the data at this location is deleted when the client is disconnected (due to closing the browser, navigating to a new page, or network issues).
Returns
Resolves when synchronization to the server is complete.
method set
set: (value: unknown) => Promise<void>;
Ensures the data at this location is set to the specified value when the client is disconnected (due to closing the browser, navigating to a new page, or network issues).
set()
is especially useful for implementing "presence" systems, where a value should be changed or cleared when a user disconnects so that they appear "offline" to other users. See Enabling Offline Capabilities in JavaScript for more information.Note that
onDisconnect
operations are only triggered once. If you want an operation to occur each time a disconnect occurs, you'll need to re-establish theonDisconnect
operations each time.Parameter value
The value to be written to this location on disconnect (can be an object, array, string, number, boolean, or null).
Returns
Resolves when synchronization to the Database is complete.
method setWithPriority
setWithPriority: ( value: unknown, priority: number | string | null) => Promise<void>;
Ensures the data at this location is set to the specified value and priority when the client is disconnected (due to closing the browser, navigating to a new page, or network issues).
Parameter value
The value to be written to this location on disconnect (can be an object, array, string, number, boolean, or null).
Parameter priority
The priority to be written (string, number, or null).
Returns
Resolves when synchronization to the Database is complete.
method update
update: (values: object) => Promise<void>;
Writes multiple values at this location when the client is disconnected (due to closing the browser, navigating to a new page, or network issues).
The
values
argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.As opposed to the
set()
method,update()
can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).Parameter values
Object containing multiple values.
Returns
Resolves when synchronization to the Database is complete.
class QueryConstraint
abstract class QueryConstraint {}
A
QueryConstraint
is used to narrow the set of documents returned by a Database query.QueryConstraint
s are created by invoking endAt, endBefore, startAt, startAfter, limitToFirst, limitToLast, orderByChild, orderByChild, orderByKey , orderByPriority , orderByValue or equalTo and can then be passed to query to create a new query instance that also contains thisQueryConstraint
.
property type
abstract readonly type: QueryConstraintType;
The type of this query constraints
class TransactionResult
class TransactionResult {}
A type for the resolve value of runTransaction.
Interfaces
interface DatabaseReference
interface DatabaseReference extends Query {}
A
DatabaseReference
represents a specific location in your Database and can be used for reading or writing data to that Database location.You can reference the root or child location in your Database by calling
ref()
orref("child/path")
.Writing is done with the
set()
method and reading can be done with theon*()
method. See https://firebase.google.com/docs/database/web/read-and-write
property key
readonly key: string | null;
The last part of the
DatabaseReference
's path.For example,
"ada"
is the key forhttps://<DATABASE_NAME>.firebaseio.com/users/ada
.The key of a root
DatabaseReference
isnull
.
property parent
readonly parent: DatabaseReference | null;
The parent location of a
DatabaseReference
.The parent of a root
DatabaseReference
isnull
.
property root
readonly root: DatabaseReference;
The root
DatabaseReference
of the Database.
interface IteratedDataSnapshot
interface IteratedDataSnapshot extends DataSnapshot {}
Represents a child snapshot of a
Reference
that is being iterated over. The key will never be undefined.
property key
key: string;
interface ListenOptions
interface ListenOptions {}
An options objects that can be used to customize a listener.
property onlyOnce
readonly onlyOnce?: boolean;
Whether to remove the listener after its first invocation.
interface Query
interface Query {}
A
Query
sorts and filters the data at a Database location so only a subset of the child data is included. This can be used to order a collection of data by some attribute (for example, height of dinosaurs) as well as to restrict a large list of items (for example, chat messages) down to a number suitable for synchronizing to the client. Queries are created by chaining together one or more of the filter methods defined here.Just as with a
DatabaseReference
, you can receive data from aQuery
by using theon*()
methods. You will only receive events andDataSnapshot
s for the subset of the data that matches your query.See https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data for more information.
property ref
readonly ref: DatabaseReference;
The
DatabaseReference
for theQuery
's location.
method isEqual
isEqual: (other: Query | null) => boolean;
Returns whether or not the current and provided queries represent the same location, have the same query parameters, and are from the same instance of
FirebaseApp
.Two
DatabaseReference
objects are equivalent if they represent the same location and are from the same instance ofFirebaseApp
.Two
Query
objects are equivalent if they represent the same location, have the same query parameters, and are from the same instance ofFirebaseApp
. Equivalent queries share the same sort order, limits, and starting and ending points.Parameter other
The query to compare against.
Returns
Whether or not the current and provided queries are equivalent.
method toJSON
toJSON: () => string;
Returns a JSON-serializable representation of this object.
Returns
A JSON-serializable representation of this object.
method toString
toString: () => string;
Gets the absolute URL for this location.
The
toString()
method returns a URL that is ready to be put into a browser, curl command, or arefFromURL()
call. Since all of those expect the URL to be url-encoded,toString()
returns an encoded URL.Append '.json' to the returned URL when typed into a browser to download JSON-formatted data. If the location is secured (that is, not publicly readable), you will get a permission-denied error.
Returns
The absolute URL for this location.
interface ThenableReference
interface ThenableReference extends DatabaseReference, Pick<Promise<DatabaseReference>, 'then' | 'catch'> {}
A
Promise
that can also act as aDatabaseReference
when returned by push. The reference is available immediately and thePromise
resolves as the write to the backend completes.
interface TransactionOptions
interface TransactionOptions {}
An options object to configure transactions.
property applyLocally
readonly applyLocally?: boolean;
By default, events are raised each time the transaction update function runs. So if it is run multiple times, you may see intermediate states. You can set this to false to suppress these intermediate states and instead wait until the transaction has completed before events are raised.
Type Aliases
type EventType
type EventType = | 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed';
One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."
type QueryConstraintType
type QueryConstraintType = | 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';
Describes the different query constraints available in this SDK.
type Unsubscribe
type Unsubscribe = () => void;
A callback that can invoked to remove a listener.
Package Files (1)
Dependencies (7)
Dev Dependencies (4)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@firebase/database
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@firebase/database)
- HTML<a href="https://www.jsdocs.io/package/@firebase/database"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6905 ms. - Missing or incorrect documentation? Open an issue for this package.