0
0
FirebaseHow-ToBeginner · 3 min read

How to Use set() in Firebase Realtime Database

Use the set() method on a database reference to write or replace data at that location in Firebase Realtime Database. It takes the data you want to save as an argument and returns a promise that resolves when the write is complete.
📐

Syntax

The set() method is called on a database reference and takes one argument: the data to write. It replaces any existing data at that location.

  • ref: A reference to the database location.
  • data: The value to save (can be object, string, number, etc.).
  • returns: A promise that resolves when the write finishes.
javascript
ref.set(data)
💻

Example

This example shows how to write a user's name and age to the Realtime Database under the path /users/user1. It uses set() to save the data and logs success or error.

javascript
import { getDatabase, ref, set } from "firebase/database";

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

set(userRef, {
  name: "Alice",
  age: 25
})
.then(() => {
  console.log('Data saved successfully.');
})
.catch((error) => {
  console.error('Failed to save data:', error);
});
Output
Data saved successfully.
⚠️

Common Pitfalls

Common mistakes when using set() include:

  • Overwriting data unintentionally because set() replaces all data at the location.
  • Not handling the promise to catch errors.
  • Using incorrect database references.

To update only part of the data without overwriting, use update() instead.

javascript
import { update } from "firebase/database";

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

// Wrong: This overwrites the entire user data
set(userRef, {
  age: 26
});

// Right: Use update() to change only age
update(userRef, {
  age: 26
});
📊

Quick Reference

set() method summary:

ActionDescription
set(ref, data)Writes or replaces data at the specified reference.
ReturnsA promise that resolves when the write is complete.
OverwritesEntire data at the reference location.
Use update() insteadTo modify parts of data without overwriting.

Key Takeaways

Use set() to write or replace data at a specific database location.
set() replaces all existing data at the reference path.
Always handle the promise returned by set() to catch errors.
Use update() to change parts of data without overwriting.
Ensure your database reference points to the correct path before calling set().