RefirebaseRefirebase

push

new

push, onChildAdded, onChildChanged — list and chat patterns.

push — new list item

push adds a child with a unique, server-generated key that sorts chronologically. Ideal for chat messages, activity feeds, and any list where order matters.

db.realtime.push
import { db } from '@/lib/firebase';

// Push a new child with an auto-generated key
const result = await db.realtime.push('messages', {
  text: 'Hello!',
  uid: 'user-123',
  sentAt: Date.now(),
});

console.log(result.key); // '-NxYZ123abc...' (auto key)

onChildAdded

Listen for new items added to a list in real time. Fires once for each existing child, then again for each new one.

onChildAdded
// Listen for new children as they arrive
const stop = db.realtime.onChildAdded('messages', (snapshot) => {
  const key = snapshot.key;      // auto-generated key
  const value = snapshot.val();  // message data
  addMessageToUI(key, value);
});

// Clean up
stop();

onChildChanged

onChildChanged
const stop = db.realtime.onChildChanged('messages', (snapshot) => {
  updateMessageInUI(snapshot.key, snapshot.val());
});

onValue (full path)

onValue
// One-shot + subscription combined
// Fires immediately with current data, then on every change
const stop = await db.realtime.onValue('inbox/user-123', (value) => {
  renderInbox(value);
});

// Unsubscribe
stop();

Presence pattern

presence
// Mark user as online
await db.realtime.set('presence/user-123', true);

// Auto-remove on disconnect
db.realtime.onDisconnect('presence/user-123').remove();
💡
For React, use the usePresence hook which handles cleanup automatically.

push parameters

ParamTypeDescription
path*stringPath to the list, e.g. 'messages' or 'rooms/abc/messages'.
data*TData to write to the new child node.

push return value

Returns

Promise<{ key: string | null } | { error }>

key is the auto-generated Firebase push key, e.g. -NxYZ123abc.