Escucha de cambios en tiempo real
Haga que su aplicación sea realmente dinámica suscribiéndose a eventos de Realtime Database, reaccionando a cambios en valores y nodos secundarios a medida que ocurren y limpiando los listeners para evitar fugas.
Escucha de cambios en tiempo real es una lección gratuita de Firebase Auth & Realtime Database Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Firebase Auth & Realtime Database Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Firebase Auth & Realtime Database Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
From Fetch to Stream
Reading data once gives you a snapshot. The power of Realtime Database is live updates: your app reacts the instant data changes on the server, with no polling.
This is done by attaching listeners to a location in the database.
The Value Event
The most common listener is value. It fires once immediately with current data, then again every time anything under that location changes.
import { getDatabase, ref, onValue } from 'firebase/database';
const db = getDatabase();
onValue(ref(db, 'scores/global'), (snapshot) => {
console.log('New value:', snapshot.val());
});Reading the Snapshot
The callback receives a DataSnapshot. Use .val() for the data, .exists() to check presence, and .key for the node name.
onValue(ref(db, 'user/42'), (snap) => {
if (snap.exists()) {
console.log(snap.key, snap.val());
}
});Child Events
For lists, value events resend the whole node on every change. Child events are more efficient, firing per item:
onChildAddedonChildChangedonChildRemoved
Using onChildAdded
onChildAdded fires once for each existing child, then for every new one. It is perfect for chat messages or feeds.
import { onChildAdded } from 'firebase/database';
onChildAdded(ref(db, 'messages'), (snap) => {
appendMessage(snap.key, snap.val());
});Reacting to Changes and Removals
Pair additions with change and removal handlers to keep your UI in sync without re-rendering everything.
import { onChildChanged, onChildRemoved } from 'firebase/database';
onChildChanged(ref(db, 'messages'), s => updateMessage(s.key, s.val()));
onChildRemoved(ref(db, 'messages'), s => removeMessage(s.key));Reading Once
Sometimes you want current data without an ongoing subscription. Use get for a one-time read instead of a listener.
import { get } from 'firebase/database';
const snap = await get(ref(db, 'config'));
console.log(snap.val());Detaching Listeners
Listeners stay active until removed, consuming bandwidth and memory. Always detach them when a screen unmounts, using the unsubscribe function returned by onValue.
const unsubscribe = onValue(ref(db, 'scores'), cb);
// later, when leaving the screen:
unsubscribe();Handling Errors
Listeners can fail, often due to Security Rules denying read access. Provide an error callback so failures are visible, not silent.
onValue(ref(db, 'private'), (snap) => render(snap), (error) => {
console.error('Read failed:', error.message);
});Performance Tips
Keep listeners efficient:
- Listen at the smallest path that has the data you need
- Prefer child events for large lists
- Never attach a value listener to the database root
A Live Counter Example
Putting it together: attach a value listener to a counter node, update the DOM in the callback, and unsubscribe on cleanup. The number changes for every connected client in real time.
const unsub = onValue(ref(db, 'visitors/count'), (snap) => {
document.getElementById('count').textContent = snap.val() ?? 0;
});Quick Check
Test your understanding of realtime listeners.
Recap
Your app can now respond to data the moment it changes.
- Use
onValuefor single nodes - Use child events for efficient lists
- Read once with
getwhen no subscription is needed - Always detach listeners and handle errors
- Listen at the narrowest useful path
Preguntas frecuentes
¿La lección «Escucha de cambios en tiempo real» es gratis?
Sí — el texto completo de «Escucha de cambios en tiempo real» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Firebase Auth & Realtime Database Apps, actualiza a CoddyKit PRO. El curso de Firebase Auth & Realtime Database Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Escucha de cambios en tiempo real»?
Haga que su aplicación sea realmente dinámica suscribiéndose a eventos de Realtime Database, reaccionando a cambios en valores y nodos secundarios a medida que ocurren y limpiando los listeners para… Practicas Firebase Auth & Realtime Database Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Firebase Auth & Realtime Database Apps?
No se requiere experiencia previa. Firebase Auth & Realtime Database Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Escucha de cambios en tiempo real»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Firebase Auth & Realtime Database Apps?
Sí. Cada lección de Firebase Auth & Realtime Database Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Fundamentos de Realtime Database
- Lectura y escritura de datos
- Estructuración de los datos
- Escucha de cambios en tiempo real