Reputation: 1502
When I call my application, I want to read a list of all the content in my Firebase Realtime DB. For this I use the useEffect function in React. But now it is the case that the data is not loaded every time, which means: If I'm lucky, data comes up, if not, I have to press the refresh button of the browser several times. Why is that so ?
import { getDatabase, ref, onValue } from "firebase/database";
React.useEffect(() => {
let array = [];
const firebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(firebaseApp);
const starCountRef = ref(db, "articel");
onValue(
starCountRef,
(snapshot) => {
snapshot.forEach((child) => {
array.push(child.val());
});
},
{
onlyOnce: true,
}
);
setArtikel(array);
}, []);
Upvotes: 1
Views: 38
Reputation: 84912
You are setting state right away, before any values come back. You need to wait until you get a snapshot, and then create the array and set state.
React.useEffect(() => {
const firebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(firebaseApp);
const starCountRef = ref(db, "articel");
onValue(
starCountRef,
(snapshot) => {
let array = [];
snapshot.forEach((child) => {
array.push(child.val());
});
setArtikel(array);
},
{
onlyOnce: true,
}
);
}, []);
Upvotes: 1