SDK v9 (modulare) β il modo moderno
SDK v9 (modular) β the modern way
import { getDatabase, ref, get } from 'firebase/database';
const db = getDatabase();
// β
Legge una volta sola β ideale per dati storici o config
async function readOnce(path) {
const snap = await get(ref(db, path));
if (snap.exists()) {
return snap.val(); // oggetto JS con i dati
}
return null;
}
// Uso
const utente = await readOnce(`users/${uid}`);
console.log(utente.nome);
import { getDatabase, ref, onValue, off } from 'firebase/database';
const db = getDatabase();
// β
Ascolta le modifiche in real-time
function listenMessages(chatId, callback) {
const chatRef = ref(db, `chats/${chatId}/messages`);
const unsub = onValue(chatRef, snap => {
const msgs = snap.exists() ? Object.values(snap.val()) : [];
callback(msgs);
});
// Restituisce la funzione di unsubscribe β chiamala quando esci dalla pagina
return unsub;
}
// Avvia ascolto
const stopListening = listenMessages('room-42', msgs => {
console.log('Nuovi messaggi:', msgs);
});
// Ferma l'ascolto (es. quando l'utente lascia la pagina)
// stopListening();
SDK v8 (compat) β se usi ancora il vecchio SDK
SDK v8 (compat) β if you're still on the old SDK
const db = firebase.database();
// Lettura una tantum (v8)
db.ref(`users/${uid}`).once('value').then(snap => {
if (snap.exists()) console.log(snap.val());
});
// Ascolto real-time (v8)
const chatRef = db.ref(`chats/room-42/messages`);
chatRef.on('value', snap => {
console.log(snap.val());
});
// Rimuovi listener
chatRef.off('value');
Quando usare quale
When to use which
| Caso d'uso | Metodo | PerchΓ© |
| Profilo utente all'apertura | get() | Dati statici, non cambiano mentre l'utente Γ¨ loggato |
| Configurazione app | get() | Leggi una volta, metti in cache locale |
| Chat in tempo reale | onValue() | I messaggi arrivano mentre l'utente Γ¨ nella pagina |
| Stato presenze online | onValue() | Cambia frequentemente e in modo imprevedibile |
| Storico ordini / log | get() | Dati passati immutabili β nessun motivo di stare in ascolto |
| Notifiche in arrivo | onValue() | Devono apparire istantaneamente senza refresh |
| Use case | Method | Why |
| User profile on load | get() | Static data, doesn't change while user is logged in |
| App configuration | get() | Read once, store locally in memory |
| Real-time chat | onValue() | Messages arrive while the user is on the page |
| Online presence | onValue() | Changes frequently and unpredictably |
| Order history / logs | get() | Immutable past data β no reason to keep listening |
| Incoming notifications | onValue() | Must appear instantly without a page reload |
Regola pratica: se il dato puΓ² cambiare mentre l'utente Γ¨ nella pagina e lui deve vederlo subito, usa onValue(). In tutti gli altri casi usa get() e risparmia connessioni e costi.
Rule of thumb: if the data can change while the user is on the page and they need to see it immediately, use onValue(). In all other cases use get() and save connections and costs.
Memory leak comune: ogni onValue() apre una connessione WebSocket che rimane attiva finchΓ© non chiami unsubscribe(). In una SPA, pulisci sempre i listener quando il componente viene smontato.
Common memory leak: every onValue() opens a WebSocket connection that stays active until you call unsubscribe(). In a SPA, always clean up listeners when the component is unmounted.
Articolo correlato
Calendario condiviso su PWA: Firebase Realtime Database e notifiche push FCM
Related article
Shared calendar on a PWA: Firebase Realtime Database and FCM push notifications
β
Articolo correlato
Catalogo file dinamico con Firebase RTDB e Storage: modal admin e race condition asincrona
Related article
Dynamic file catalogue with Firebase RTDB and Storage: admin modal and async race condition
β