0
0
FirebaseHow-ToBeginner · 3 min read

How to Use once() in Firebase Realtime Database

Use the once() method on a Firebase Realtime Database reference to read data a single time. It returns a promise that resolves with a snapshot of the data at that location, without listening for future changes.
📐

Syntax

The once() method is called on a database reference and takes an event type, usually 'value', to read the data once.

It returns a promise that resolves with a DataSnapshot containing the data at that location.

javascript
ref.once('value').then(snapshot => {
  const data = snapshot.val();
  // use data
});
💻

Example

This example shows how to read user data once from the path /users/user1 and log it to the console.

javascript
import { getDatabase, ref, get } from 'firebase/database';

const db = getDatabase();
const userRef = ref(db, 'users/user1');

get(userRef).then(snapshot => {
  if (snapshot.exists()) {
    console.log('User data:', snapshot.val());
  } else {
    console.log('No data available');
  }
}).catch(error => {
  console.error('Error reading data:', error);
});
Output
User data: { name: 'Alice', age: 30 }
⚠️

Common Pitfalls

  • Using on() instead of once() when you only want to read data once, which causes continuous listening and extra costs.
  • Not handling the case when data does not exist, leading to errors when calling snapshot.val().
  • Forgetting to catch errors from the promise, which can cause unhandled promise rejections.
javascript
/* Wrong: Using on() for one-time read */
ref.on('value', snapshot => {
  console.log(snapshot.val());
});

/* Right: Using once() or get() for one-time read */
ref.once('value').then(snapshot => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  }
});
📊

Quick Reference

Summary tips for using once() in Firebase Realtime Database:

  • Use once('value') or get(ref) to read data once.
  • Always check snapshot.exists() before accessing data.
  • Handle errors with catch() on the promise.
  • Do not use on() if you only need a single read.

Key Takeaways

Use once('value') or get(ref) to read data a single time from Realtime Database.
Always check if data exists with snapshot.exists() before using snapshot.val().
Handle errors by adding catch() to the promise returned by once() or get().
Avoid using on() for one-time reads to prevent unnecessary listeners and costs.
once() returns a promise that resolves with a DataSnapshot of the data at the reference.