File size: 1,148 Bytes
f5071ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import { collection, onSnapshot } from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { db } from '../config/firebase';
const useGetData = (colName) => {
const [data, setData] = useState(null);
const [loading, setloading] = useState(true);
const [err, setErr] = useState(false);
useEffect(() => {
let colRef;
if (colName === 'posts') {
colRef = collection(db, 'posts');
} else if (colName === 'users') {
colRef = collection(db, 'users');
}
onSnapshot(colRef, { includeMetadataChanges: true }, (snapshot) => {
if (!snapshot.metadata.hasPendingWrites) {
if (snapshot.docs.length === 0) {
setloading(false);
setErr(true);
return;
}
setloading(false);
setErr(false);
const newData = [];
snapshot.docs.forEach((doc) => {
newData.push({ ...doc.data(), id: doc.id });
});
setData(newData);
}
});
}, [colName]);
return { data, loading, err };
};
export default useGetData;
|