RNFirebase mimics the [Web Firebase SDK Realtime Database](https://firebase.google.com/docs/database/web/read-and-write), whilst
providing support for devices in low/no data connection state.
All real time Database operations are accessed via `database()`.
Basic read example:
```javascript
firebase.database()
.ref('posts')
.on('value', (snapshot) => {
const value = snapshot.val();
});
```
Basic write example:
```javascript
firebase.database()
.ref('posts/1234')
.set({
title: 'My awesome post',
content: 'Some awesome content',
});
```
## Unmounted components
Listening to database updates on unmounted components will trigger a warning:
> Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
It is important to always unsubscribe the reference from receiving new updates once the component is no longer in use.
This can be achived easily using [Reacts Component Lifecycle](https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle) events:
Always ensure the handler function provided is of the same reference so RNFirebase can unsubscribe the ref listener.
```javascript
class MyComponent extends Component {
constructor() {
super();
this.ref = null;
}
// On mount, subscribe to ref updates
componentDidMount() {
this.ref = firebase.database().ref('posts/1234');
this.ref.on('value', this.handlePostUpdate);
}
// On unmount, ensure we no longer listen for updates
componentWillUnmount() {
if (this.ref) {
this.ref.off('value', this.handlePostUpdate);
}
}
// Bind the method only once to keep the same reference
Bear in mind that security rules live on the firebase server and **not in the client**. In other words, when offline, your app knows nothing about your database's security rules. This can lead to unexpected behaviour, which is explained in detail in the following blog post: https://firebase.googleblog.com/2016/11/what-happens-to-database-listeners-when-security-rules-reject-an-update.html
Some examples of behaviour you may not expect but may encounter are:
- Values that should not be readable, according to your security rules, are readable if they were created on the same device.
- Values are readable even when not authenticated, if they were created on the same device.
- Locations are writable even when they should not be, according to your security rules. This is more likely to cause unwanted behaviour when your app is offline, because when it is *online* the SDK will very quickly roll back the write once the server returns a permission error.