Front end Development
How to Connect Firebase Realtime Database to a React App
June 27, 2022In this article, I’ll show you the way to connect firebase to a react app with folder structure.
“The world needs dreamers and the world needs doers. But above all, the world needs dreamers who do.” — Sarah Ban Breathnach
I’m not telling you how to open a project in firebase or create react app. But don’t freak out, I’ll mention important parts.
Let’s get started!
Firstly we’ll set up Firebase,
After logging in to firebase and adding a new project, a project overview page will appear. Now our journey starts. Click the setting icon, then project settings next to the ‘project overview’ text.
Scroll the page until you see your apps section. Select </> (web app). Give a name, and click ‘Register App’. (If you want Firebase Hosting, select the option. This is not our topic today but someday will be.)
Firebase will generate your config variable.
Go back to react project and install firebase SDK to the project.
npm install firebase
Create a new folder named ‘src’. This folder will be our main folder to keep the folder organized and clean. And create another folder named ‘utils’ in src. In this folder, we’ll keep our utility functions such as ‘firebase.js’ which you need to create now.
I’ll talk about react folder structure widely in another article. Follow me and don’t miss upcoming articles.
Copy and paste that firebase-generated config to the firebase.js file. And add the following line import section. We are adding this line because we will get the database in this file and export it.
import { getDatabase } from “firebase/database”;
So our next move is after initializing the app with the config variable, initializing the database, and exporting it;
export const db = getDatabase(app);
So after all this, your firebase file looks like this:
I strongly suggest that use environment variables and keep your keys hidden. Look at this link.
It’s simple as that. Everything is ready now. Now we can use it anywhere in our app!
In the file, you need the fetch data, you can use this utility.
Import this util and some firebase methods then use with reference method from firebase;
import { db } from “../../utils/firebase”; import { onValue, ref } from “firebase/database”;
Eventually, your code looks like something like this;
P.S: Do not use the index in keys due to performance considerations. Check out the official documentation.
P.S: The reason we use onValue method in useEffect’s cleanup section is that this method is an unsubscribe method, which means after the job is done connection will be closed, and in this way, we prevent memory leaks on our app.
Hope you enjoyed it!
Author: Mahir Uslu