A DataSnapshot API contains data from a database location.
Any time you read data from the database, you receive the data as a DataSnapshot.
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 the set() method on a reference directly).
|
⇓ Showing user #1 |
value
event will trigger once with the initial data stored at this location, and then trigger again each time the data changes.
The DataSnapshot passed to the callback will be for the location at which on()
was called.
It will not trigger until the entire contents has been synchronized.
If the location has no data, it will be triggered with an empty DataSnapshot (val()
will return null).
on()
or once()
.
You can extract the contents of the snapshot as a JavaScript object by calling the val()
method.
Object.values()
method returns an array of a given object’s own enumerable property values, in the same order as that provided by a for...in
loop.
<script> // // Function to get form values // function getInputVal( input ) { return document.getElementById( input ).value; } // // Show a user. // function showUser( ) { var ID = getInputVal( 'ID' ); var ref = firebase.database( ).ref( 'users/' + ID ); ref.on( "value", function( snapshot ) { const data = snapshot.val( ); var out = "ID: " + ID + "Name: " + Object.values(data)[1]; out += "Email: " + Object.values(data)[0]; document.getElementById( 'result' ).innerHTML = out; }, function ( error ) { document.getElementById( 'result' ).innerHTML = "Error"; } ); return( false ); } </script> |
“You cannot teach a man anything, you can only help him find it within himself.” ― Galileo |