Easy almost-full-stack app with React and firebase
Creating a full stack application sounds very difficult for people and indeed it is. It requires a lot of knowledge and huge amount of logics, but this does not mean it is impossible for beginners to implement these functionalities thanks to services called like BaaS or PaaS. There are lots of options to choose to implement backend functionalities easily, but in this article, I’ll explain how to do it with firebase because it is one of the most common ones now and very easy to use.
To learn how to use the service, let’s create a simple app that you can get data from a database and show the data stored in the database on the browser.
Here is the steps to follow.
- Create a React app
- Register an app on firebase
- Connect firebase to React
- Get data from firebase and display
Let’s dive into “full stack” world!
1. Create a React App
First things first, let’s create a React app using create-react-app command on your terminal.
npx create-react-app [APP_NAME]
Let’s open your editor and create List.jsx file with basic default export format under src
directory as a main component we work on. Once done, you should see these directories and files on your editor.
Also, don’t forget to import and use List component in App component like below.
If done, leave React for now and move on to firebase setting.
2. Register an app on firebase
Visit https://firebase.google.com/
and click go to console
button on top right.
If this is the first time for you to use firebase, just click Create a project button
on the page.
Then you should be asked to enter your project name. Just name as you like and click continue.
In the next page, you’ll asked if you want to enable google analytics, but it’s up to you because the app we are creating is just for practice and it does not really matter.
Once you hit a Create
button and wait for a bit, you’ll see home screen of your project. To let firebase know that we are creating web app, click </>
icon.
Then you’ll be asked to enter your app name. You can name it as you want just like we did for a project name. Once you click Register app
andContinue to the console
button, it is time to set up database called firestore.
On console page, you should be able to see Firestore on the sidebar.
If you see Cloud Firestore page, just click Create database
button to create a database. Then you’ll see a popup that asks you if you want to start in “production mode” or “test mode” but just choose “test mode” and hit Next
button.
Next up, you’ll be asked to choose database location. It doesn’t really matter but people basically choose their region or default location. Choose whatever you want and hit Next
button.
On the main page of Firestore, let’s create a collection called “items”. To create a collection, just click Start collection
on left side of the screen. Then you’ll see a popup that asks you Collection ID. Let’s do this with items as I mentioned earlier.
Next, you’ll be asked to create the first document. For this screen, just click Auto-ID
and set Field
as “item” with value “watermelon” and hit Save
.
Then you’ll see one sample record on items collection.
This is pretty mush about firebase setup.
3. Connect firebase to React
- Check config info of firebase
In order to connect firebase to React, you need to know config info of your firebase. Here is the way to check yours
Click gear icon on the side bar → Choose project setting→ go to the very bottom of the page
The contents of the variable named firebaseConfig
is your config info.
There is one thing that you should be aware of about this information. Do NOT share these information with public like on github. Some say it is not a problem to share these but they should be hidden just in case. Just put them in .env
file to hide them from github. These variables are called enviromental variables. Don’t worry, I’ll explain how to do it in a bit.
It is time to work on your editor! Hang on!
2. Set up connection with firebase on React
First, you need to install package named firebase
so you can use lots of functions provided by firebase.
npm i firebase
Then, let’s put config info into .env
file so they are recognized as environmental variables and read the values from another file. In the file put variable name and value like below.
REACT_APP_VARIABLE_NAME=VALUE
Each value should be the ones you confirmed previous step. Once you set up all environmental variables, the contents of .env
should look like so.
Next up, create a directory named firebase and a file named index.js under src
directory. index.js is where all logics related to firebase go. You can think of it as like a connecting point of firebase and React.
In index.js
file, import 2 packages and export 1 thing.
[index.js]import firebase from 'firebase/app';
import 'firebase/firestore';const firebaseConfig = {
apiKey: process.env.REACT_APP_APLI_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID
}firebase.initializeApp(firebaseConfig);export const db = firebase.firestore()
In firebaseConfig object, you need to pass keys that you saw on firebase (apiKey, authDomain, etc). The values of each key is where we read the environmental variables we set earlier. By putting process.env.
before variable name, React automatically read the value inside .env
file. Since we created this app by create-react-app
, the system has this feature. We usually need to install some package like dotenv
to read environmental variables, but it’s not necessary for app created by create-react-app
.
Now React and firebase should be connected successfully.
So far, index.js in firebase directory looks like so.
4. Get data from firebase and displa
First of all, let’s try to get data from firestore. In List.jsx file, set a state named itemData
and create a function named getData
which access firestore and get data from it and set the data to the itemData
. I know it sounds a lot of work, but each operation is not really hard to understand.
Also, do not forget to import useEffect, useState form react and db from the file we worked on earlier.
[List.jsx]import React, {useEffect, useState} from "react";
import {db} from "./firebase/index";const [itemData, setItemData] = useState([]);const getData = async() => {
const itemRef = await db.collection("items")
itemRef.get().then(snapshots => {
const itemArray = snapshots.docs.map(doc => doc.data().item)
setItemData(itemArray)
}useEffect(() => {
getData()
}, [])
It might look a bit overwhelming, but these operations are totally simple.
In getData function, we created a variable named itemRef that can be used when we access and execute any operation on firestore. Then, we get an array of certain amount of data that contain our target information like item: watermelon
, by using get()
. Since out target information is watermelon, we iterate through an array of snapshots.docs
and return the string watermelon by doc.data().item
. Lastly, set the new array to itemData state.
The whole code of List.jsx should look like so.
You are almost there!
What’s left is to display the data on your screen. Now the data is store in the state, itemData
. Just put it inside div
with inside {}
.
<div>{itemData}<div>
Once you do npm start
, your screen should look like below.
It’s not fancy at all at this moment, but Hopefully you grabbed the concept of accessing database from React.
Thank you for reading and see you soon!