Firebase Real Time Database
Overview
- syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
- bindToState: One way data binding. When your Firebase endpoint changes, the property on your state will update as well.
- listenTo: When your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
- fetch: Retrieve data from Firebase without setting up any binding or listeners.
- post: Add new data to Firebase.
- push: Push new child data to Firebase.
- update: Update child data using only the referenced properties
- remove: Remove data from Firebase
- removeBinding: Remove a Firebase listener before the component unmounts if you need to. (Listeners are automatically cleaned up when component unmounts)
- reset: Removes all of the Firebase listeners.
createClass(firebaseDatabase)
Purpose
Accepts an initialized firebase database object
Arguments
- initialized firebase database (Object)
Return Value
An instance of re-base.
Example using all of firebase
var Rebase = require('re-base');
var firebase = require('firebase');
var app = firebase.initializeApp({
apiKey: 'apiKey',
authDomain: 'projectId.firebaseapp.com',
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'bucket.appspot.com',
messagingSenderId: 'xxxxxxxxxxxxxx'
});
var base = Rebase.createClass(app.database());
Example using only the firebase database component
var Rebase = require('re-base');
var firebase = require('firebase/app');
var database = require('firebase/database');
var app = firebase.initializeApp({
apiKey: 'apiKey',
authDomain: 'projectId.firebaseapp.com',
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'bucket.appspot.com',
messagingSenderId: 'xxxxxxxxxxxxxx'
});
var db = firebase.database(app);
var base = Rebase.createClass(db);
initializedApp
Purpose
This property contains the initialized firebase app that was passed into re-base. You can access any of the firebase services that you are using off this object. For instance, if you want to use some firebase database
methods that re-base doesn't have helpers for or if you are using the auth
service and want to quickly access it off of re-base.
timestamp
Purpose
This property contains an object that you can use when adding data that will be converted to a timestamp by Firebase. See the docs for more info.
syncState(endpoint, options)
Purpose
Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.
Arguments
- endpoint (String)
- The relative Firebase endpoint to which you'd like to bind your component's state
- options (Object)
- context: (Object - required) The context of your component
- state: (String - required) The state property you want to sync with Firebase; can be an arbitrarily nested property a là
foo.bar
- defaultValue: (String|Boolean|Number|Object - optional) A default value to set when the Firebase endpoint has no value (i.e., on init) (use this if you want a value other than an empty object or empty array)
- asArray: (Boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
- keepKeys: (Boolean - optional) will keep any firebase generated keys intact when manipulating data using the asArray option.
- queries: (Object - optional) Queries to be used with your read operations. See Query Options for more details.
- then: (Function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change
this.state.loading
to false. - onFailure: (Function - optional) A callback function that will be invoked if the current user does not have read or write permissions at the location.
Return Value
An object which you can pass to removeBinding
if you want to remove the listener while the component is still mounted.
Example
componentDidMount(){
base.syncState(`shoppingList`, {
context: this,
state: 'items',
asArray: true
});
}
addItem(newItem){
this.setState({
items: this.state.items.concat([newItem]) //updates Firebase and the local state
});
}
bindToState(endpoint, options)
Purpose
One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.
Arguments
- endpoint (String)
- The relative Firebase endpoint that you'd like to bind to your component's state
- options (Object)
- context: (Object - required) The context of your component
- state: (String - required) The state property you want to sync with Firebase; can be an arbitrarily nested property a là
foo.bar
(no arrays) - asArray: (Boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
- queries: (Object - optional) Queries to be used with your read operations. See Query Options for more details.
- then: (Function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with bindToState) to change
this.state.loading
to false. - onFailure: (Function - optional) A callback function that will be invoked if the current user does not have read permissions at the location.
Return Value
An object which you can pass to removeBinding
if you want to remove the listener while the component is still mounted.
Example
componentDidMount(){
base.bindToState('tasks', {
context: this,
state: 'tasks',
asArray: true
});
}
listenTo(endpoint, options)
Purpose
Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.
Arguments
- endpoint (String)
- The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
- options (Object)
- context: (Object - required) The context of your component
- asArray: (Boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
- then: (Function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
- onFailure: (Function - optional) The callback function that will be invoked if the current user does not have read permissions at the location.
- queries: (Object - optional) Queries to be used with your read operations. See Query Options for more details.
Return Value
An object which you can pass to removeBinding
when your component unmounts to remove the Firebase listeners.
Example
componentDidMount(){
base.listenTo('votes', {
context: this,
asArray: true,
then(votesData){
var total = 0;
votesData.forEach((vote, index) => {
total += vote
});
this.setState({total});
}
})
}
fetch(endpoint, options)
Purpose
Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.
Arguments
- endpoint (String)
- The relative Firebase endpoint which contains the data you're wanting to fetch
- options (Object)
- context: (Object - optional) The context of your component
- asArray: (Boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
- then: (Function - optional) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
- onFailure: (Function - optional) The callback function that will be invoked with an error that occurs reading data from the specified endpoint
- queries: (Object - optional) Queries to be used with your read operations. See Query Options for more details.
Return Value
A Firebase Promise which resolves when the write is complete and rejects if there is an error
Example
Using callback
getSales(){
base.fetch('sales', {
context: this,
asArray: true,
then(data){
console.log(data);
}
});
}
Using Promise
getSales(){
base.fetch('sales', {
context: this,
asArray: true
}).then(data => {
console.log(data);
}).catch(error => {
//handle error
})
}
post(endpoint, options)
Purpose
Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data
Arguments
- endpoint (String)
- The relative Firebase endpoint that you'd like to update with the new data
- options (Object)
- data: (Any - required) The data you're wanting to persist to Firebase
- then: (Function - optional) A callback that will get invoked once the new data has been saved to Firebase. If there is an error, it will be the only argument to this function.
Return Value
A Firebase Promise which resolves when the write is complete and rejects if there is an error
Example
Using callback
addUser(){
base.post(`users/${userId}`, {
data: {name: 'Tyler McGinnis', age: 25},
then(err){
if(!err){
Router.transitionTo('dashboard');
}
}
});
}
Using promise
addUser(){
base.post(`users/${userId}`, {
data: {name: 'Tyler McGinnis', age: 25}
}).then(() => {
Router.transitionTo('dashboard');
}).catch(err => {
// handle error
});
}
push(endpoint, options)
Purpose
Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key
Arguments
- endpoint (String)
- The relative Firebase endpoint that you'd like to push the new data to
- options (Object)
- data: (Any - required) The data you're wanting to persist to Firebase
- then: (Function - optional) A callback that will get invoked once the new data has been saved to Firebase. If there is an error, it will be the only argument to this function.
Return Value
A Firebase ThenableReference which is defined by Firebase as a "Combined Promise and reference; resolves when write is complete, but can be used immediately as the reference to the child location."
Example
Using callback
//
addBear(){
var immediatelyAvailableReference = base.push('bears', {
data: {name: 'George', type: 'Grizzly'},
then(err){
if(!err){
Router.transitionTo('dashboard');
}
}
});
//available immediately, you don't have to wait for the callback to be called
var generatedKey = immediatelyAvailableReference.key;
}
Using Promise interface
//
addBear(){
var immediatelyAvailableReference = base.push('bears', {
data: {name: 'George', type: 'Grizzly'}
}).then(newLocation => {
var generatedKey = newLocation.key;
}).catch(err => {
//handle error
});
//available immediately, you don't have to wait for the Promise to resolve
var generatedKey = immediatelyAvailableReference.key;
}
update(endpoint, options)
Purpose
Allows you to update data at a Firebase endpoint changing only the properties you pass to it.
Warning: calling update with options.data
being null will remove all the data at that endpoint
Arguments
- endpoint (String)
- The relative Firebase endpoint that you'd like to update
- options (Object)
- data: (Any - required) The data you're wanting to persist to Firebase
- then: (Function - optional) A callback that will get invoked once the new data has been saved to Firebase. If there is an error, it will be the only argument to this function.
Return Value
A Firebase Promise which resolves when the write is complete and rejects if there is an error
Example
Using callback
// bears endpoint currently holds the object { name: 'Bill', type: 'Grizzly' }
base.update('bears', {
data: { name: 'George' },
then(err) {
if (!err) {
Router.transitionTo('dashboard');
//bears endpint is now {name: 'George', type: 'Grizzly'}
}
}
});
Using Promise
// bears endpoint currently holds the object { name: 'Bill', type: 'Grizzly' }
base
.update('bears', {
data: { name: 'George' }
})
.then(() => {
Router.transitionTo('dashboard');
})
.catch(err => {
//handle error
});
remove(endpoint, callback)
Purpose
Allows you to delete all data at the endpoint location
Arguments
- endpoint (String)
- The relative Firebase endpoint that you'd like to delete data from
- callback (Function - optional)
- A callback that will get invoked once the data is successfully removed Firebase. If there is an error, it will be the only argument to this function.
Return Value
A Firebase Promise which resolves when the deletion is complete and rejects if there is an error
Example
Using callback
base.remove('bears', function(err) {
if (!err) {
Router.transitionTo('dashboard');
}
});
Using Promise
base
.remove('bears')
.then(() => {
Router.transitionTo('dashboard');
})
.catch(error => {
//handle error
});
removeBinding(ref)
Purpose
Clean up a listener. Listeners are automatically cleaned up when components unmount, however if you wish to remove a listener while the component is still mounted this will allow you to do that. An example would be if you want to start listening to a new endpoint in response to a prop change.
Arguments
- ref (Object)
- The return value of
syncState
,bindToState
, orlistenTo
- The return value of
Return Value
No return value
Example
componentDidMount(){
this.ref = base.syncState('users', {
context: this,
state: 'users'
});
}
componentWillUnmount(){
base.removeBinding(this.ref);
}
reset()
Purpose
Removes every Firebase listener and resets all private variables.
Arguments
No Arguments
Return Value
No return value
Using Firebase Queries
Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.
Queries are accepted in the options
object of each read method (syncState
, bindToState
, listenTo
, and fetch
). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:
base.syncState('users', {
context: this,
state: 'users',
asArray: true,
queries: {
orderByChild: 'iq',
limitToLast: 3
}
});
The binding above will sort the users
endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users
state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.