Fetching Data from your Firebase DB
I’m working on a new project (again), and it’s time to use something new (again). At my current job, I’m constantly reaching out to people across the organization through different avenues (email, Teams, phone 🤢). It gave me the idea to try and build my own chat app with React.
The last thing I built was more frontend focused, so I wanted to focus on the backend this time.
I’ve previously used Rails as my backend in my projects, but I wanted to try something new.
I came across Firebase and decided to try to use it to create my database.
Their docs give perfect instructions on how to download Firebase to your project and set up your database (DO THIS FIRST !!)— but it took a little longer for me to figure out how to fetch data from my new database (I stumbled across a couple of errors that may be related to the different versions of Firebase)
Here’s how I did it —
I had a firebase.js file that contained all of my setup information. Including my database.
- You start by importing firestore and exporting your declared database so that it can be used throughout your project.
import {getFirestore} from “firebase/firestore”export const database = getFirestore();
2. Head over to whichever component you want to fetch the data in.
We’re going to have to import your database from the firebase.js file
import {database} from “../firebase”;
In that same file, we will also import getDocs and collection.
getDocs is provided by firebase, it grabs the documents in your database.
collection is literally the collection of documents you created in your database. In this case, we’re grabbing my messages collection
import { getDocs, collection } from "firebase/firestore";
3. I declared a const called collectionRef that stored the information needed to access the collection. I also set up the state of the messages using the useState hook.
const collectionRef = collection(database, “messages”)const [messages, setMessages] = useState([]);
4. Finally, we’re ready to fetch the data from the database.
useEffect(() => {getDocs(collectionRef).then((snapshot) => {setMessages(snapshot.docs.map(doc => doc.data()))})}, [])
My project isn’t finished yet, but I was able to render my test messages from the database onto my page.
Now, it’s up to you how you choose to display this data.
✨✨✨And that’s it!
Tish⚡️🎧🌙