I’ve tried to connect firestore with react with this code and it show nothing
I’ve tried real-time database and it works but on firestore it won’t
I’m a newbie in firebase, If you know how to connect firestore with react.
When I execute the code it show “Uncaught FirebaseError: “projectId” not provided in firebase.initializeApp.”
import { useState, useEffect } from 'react';
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, addDoc, getDocs } from 'firebase/firestore';
const firebaseConfig = {
// Your Firebase configuration
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
function App() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const collectionRef = collection(db, 'Name');
const snapshot = await getDocs(collectionRef);
if (snapshot.empty) {
console.log("No data available");
} else {
const firstDoc = snapshot.docs[0];
setData(firstDoc.data());
}
};
fetchData();
}, []);
const handleAddData = async (newData) => {
try {
const collectionRef = collection(db, 'Name');
const docRef = await addDoc(collectionRef, newData);
console.log("Data added successfully with ID:", docRef.id);
} catch (error) {
console.error("Error adding data:", error);
}
};
return (
<div>
{data ? (
<div>
<h2>Your Data</h2>
<p>Key: {data.key}</p>
<p>Value: {data.value}</p>
</div>
) : (
<p>Loading data...</p>
)}
<button onClick={() => handleAddData({ newKey: "newValue" })}>Add New Data</button>
</div>
);
}
export default App;
New contributor
Nirina fenitra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.