How to fetch from the database in Firebase
- #Firebase
- #Firestore
- #React.js
call-n
This article shows how to use Firestore in your react.js app, Fetching documents the simple way from the database. Code is found on GitHub for reference.
Click here to get to final solution
The setup of connecting to the database and configs.
First of all you should have your Firebase project setup and configed. You can find how to do that in this article, How to setup Firebase in your code.
After this you need to add the following code to your original config file:
// import the getFirestore function
import { getFirestore } from 'firebase/firestore'
// and register the db on the app
const db = getFirestore(app)
// then export the db for later usage
export { db }
And the final result when these rows are added:
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore' // added row
const firebaseConfig = {
apiKey: "AIzaSyC87utLU93uTFRaXCLUVmEDLkn9JBl_px4",
authDomain: "example-fac5e.firebaseapp.com",
projectId: "example-fac5e",
storageBucket: "example-fac5e.appspot.com",
messagingSenderId: "1043671646322",
appId: "1:1043671646322:web:ce7c55c505179e9e3242eb"
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app) // added row
export { db } // added row
Broilerplate for the following code
This is just the simple code we will be building on. This should be placed in the App.js for simplicity, the automatically generated file by create-react-app.
I have imported the firestore package, our config, added a state and a useEffect for later fetching of data.
import { useEffect, useState } from 'react'
// Firebase imports
import { db } from './Firebase/config'
import { collection, getDocs } from 'firebase/firestore'
function App() {
const [sodas, setSodas] = useState(null)
useEffect(() => {
}, [])
return (
<div className="App">
lol
</div>
);
}
export default App;
Fetching data in Firestore
The following code shows how to fetch documents from a collection in Firestore.
`collection`
takes two parameters, first the db connection we made before and then the name of the collection in our database `sodas`
in this case.
`getDocs`
takes an query, the current query we gave gets all the data inside the collection of sodas. This only calls one time so there is no realtime data, you can read more about firebase database.
`let results`
is just a temporary variable we use to store the docs we get back. After we've looped over all the docs we set the state to results to save our data.
const [sodas, setSodas] = useState(null)
useEffect(() => {
const query = collection(db, 'sodas')
getDocs(query)
.then((snapshot) => {
let results = []
snapshot.docs.forEach(doc => {
results.push({id: doc.id, ...doc.data()})
})
setSodas(results)
})
}, [])
The finished code with everything above attached.
Finished code
import { useEffect, useState } from 'react'
// Firebase imports
import { db } from './Firebase/config'
import { collection, getDocs } from 'firebase/firestore'
function App() {
const [sodas, setSodas] = useState(null)
useEffect(() => {
const ref = collection(db, 'sodas')
getDocs(ref)
.then((snapshot) => {
let results = []
snapshot.docs.forEach(doc => {
results.push({id: doc.id, ...doc.data()})
})
setSodas(results)
})
}, [])
console.log(sodas)
return (
<div className="App">
lol
</div>
);
}
export default App;
And then the `console.log`
should print something that looks like this:
Array(3) [ {…}, {…}, {…} ]
0: Object { id: "0Odgq1LVVygYaQNUrtOa", size: 0.75, title: "sprite" }
1: Object { id: "OXWjcMPsQbz5QXhTJWQY", size: 0.5, title: "fanta" }
2: Object { id: "zF57LMh73uPs0K1tf0tD", size: 1.5, title: "coca-cola" }
length: 3
And if you want to render it out to the dom, just use a `.map`
on the sodas state and you will have everything you need.
And that was all for the simple fetch in Firestore, want to read more on Firestore? Check out all articles on my blog ☂️.