It was easy to get up and running with React and Vite but what about connecting our project to a data source? Lets do it and see how we end up.
We'll use Firestore as our backend. Firestore adds real-time capabilities and a scalable backend to our application. And its SDK is easy to use.
To add Firebase to our react app, we first have to create a Firebase project. Head on over to the firebase console and click Add Project, provide a project name, and you're ready for to go.
Once the project is created you'll want to add Firebase to your web app. Register the app by giving it a nickname. Then click Register App. Next, we'll see instructions on how to add the Firebase SDK to our app. Copy this entire configuration, we'll need it in a minute.
Back over to our terminal and inside our react-vite-firebase project...
% pnpm install firebase
This'll install Modular Firebase, as opposed to Namespaced Firebase. Modular gives us tree shaking which removes unused code from your build resulting in a smaller bundle and faster app. Read more about the differences here. Once that is done installing we'll need to initialize Firebase in our app.
Open up the react-vite-firebase project in your favorite IDE. Under src
directory we'll create a new file and name it firebase.config.ts
. Paste in the configuration. There are two additional lines of code to add. First, import getFirestore
:
import { getFirestore } from "firebase/firestore"
and then at the bottom of the file lets export our db:
export const db = initializeApp(firebaseConfig)
Now we can reference our db from our App.tsx
file.
Lets get to it. Inside App.tsx
add:
import { doc, getDoc } from "firebase/firestore"
We'll use these methods to query Firestore.
Also import your db:
import { db } from './firebase.config'
Then create a useEffect
hook and paste this in. Replace YOUR-COLLECTION
and YOUR-DOC-ID
with a collection name and a doc id from your Firestore.
useEffect(() => {
async function getData() {
const docRef = doc(db, "YOUR-COLLECTION", "YOUR-DOC-ID");{/n}
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// docSnap.data() will be undefined in this case
console.log("No such document!");
}
}
getData()
}, [])
Sorry, I know that useEffect
formatting is gnarly. Just go with it.
Fire up our Vite app by running % pnpm run dev
, open up the console, and you should see your document data.
Perfecto. I hope this worked for you!
In my next post about React + Vite + Firebase we'll set up the local emulator. Right now you're querying the production database. While the free tier is generous I do recomend running the Firestore database locally. Check back soon for part 3!
Thanks for reading.