I have a database with one collection and a document, I’m trying to display the data – and nothing happens (even nothing is displayed in the console). With this authorization/registration they work
component:
import { db } from "../../firebase"
import { collection, getDocs } from "firebase/firestore";
function MainPage(props: IProps) {
async function getCities() {
const citiesCol = collection(db, 'test');
const citySnapshot = await getDocs(citiesCol);
const cityList = citySnapshot.docs.map(doc => doc.data());
console.log(cityList);
}
useEffect(() => {
getCities()
}, [])
return <h1>TEST</h1>
}
export default MainPage;
firebase.ts:
import { getFirestore } from 'firebase/firestore';
import { initializeApp } from 'firebase/app';
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: import.meta.env.VITE_apiKey,
authDomain: import.meta.env.VITE_authDomain,
projectId: import.meta.env.VITE_projectId,
storageBucket: import.meta.env.VITE_storageBucket,
messagingSenderId: import.meta.env.VITE_messagingSenderId,
appId: import.meta.env.VITE_appId
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
db in firebase:
enter image description here
I try this code then auth, but don’t work too. I see in console only “No Items in Watchlist”
firebase.ts:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import firebaseConfig from "./config/firebaseConfig";
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp); // For Authentication
const db = getFirestore(firebaseApp); // For Using Database
export { auth, db };
component:
import { onAuthStateChanged } from "firebase/auth";
import { auth, db } from "./firebase";
import { onSnapshot, doc } from "firebase/firestore";
function MainPage() {
const auth=getAuth();
useEffect(() => {
onAuthStateChanged(auth, (item) => {
if (item) setUser(item);
else setUser(null);
});
}, []);
useEffect(() => {
if (user) {
const ref= doc(db, "test", user?.uid);
var unsubscribe = onSnapshot(ref, (item) => {
if (item.exists()) {
console.log(item.data());
} else {
console.log(**"No Items in Watchlist"**);
}
});
return () => {
unsubscribe();
};
}
}, [user]);
return <h1>TEST</h1>
}
export default MainPage;