I’m trying to get live data from Firebase and I build a listener with onSnapshot so I can display it on my React Native app.
Everything is working fine, like submitting the data to FB.
But when I’m trying to get the data from FB and display it on my React Native app, it’s not working.
It’s returning an empty array.
When I console.log(q)
or console.log(collectionRef)
, it’s working perfectly fine. (But not returning the keys ofcourse)
Any help or advice will be much appreciated.
export default function Home(){
const [caretubos, setCaretubos] = React.useState([]);
const navigation = useNavigation();
React.useEffect(() => {
const collectionRef = collection(database, 'users');
const q = query(collectionRef, orderBy('createdAt','desc'));
const unsubscribe = onSnapshot(q, querySnapshot =>{
console.log('querySnapshot unsubscribe');
setCaretubos(
querySnapshot.docs.map(doc => ({
id: doc.id,
nombre: doc.data().nombre,
cantidad: doc.data().cantidad,
pretexto: doc.data().pretexto,
createAt: doc.data().createAt
}))
);
});
return unsubscribe;
},[])
console.log(caretubos);
2
Answers
I fixed it myself. I had problems with the folder importing stuff.
It looks like, based on the documentation of
onSnapshot
, that function would only be called when there are updates made to the underlying data after the first snapshot is created.I recognize that this documentation is ambiguous in interpretation, and it is unclear if immediately creating a snapshot means that your
onSnapshot
callback gets called or if it just means that a "baseline of comparison" is immediately created so that when updates occur, they’re known and then the callback can be called.It sounds like this means that your actual
onSnapshot
callback doesn’t get called the first time, but only on updates. You may need to include an initialsetCaretubos
call as well in your effect.:Additionally, your
console.log(caretubos);
statement at the bottom will return an empty array the first time before the state is set due to the asynchrony ofuseEffect
.