How to connect firebase database (firestore) to react
#tutorialSteps#
-
Go to firebase console and create a new project (or open an existing project). You don't need to enable Google Analytics for your Firebase project.
-
Click on the web icon on Project Overview
-
Click on register app and copy the code for your configuration. Your configuration will look like this:
-
In your react project, create a file named
firebase.js
in the same directory asApp.js
and paste the code there. -
Import
getFirestore
in firebase.js usingimport { getFirestore } from "firebase/firestore";
, addconst firestore = getFirestore(app);
afterinitializeApp
and finally export thisfirestore
. Your code should now look like this:
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore'; // add this
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: 'AIzaSyAlJdfLqGwKF8lFrxyBsjlK7oKwcwOrqDs',
authDomain: 'temp-379c3.firebaseapp.com',
projectId: 'temp-379c3',
storageBucket: 'temp-379c3.appspot.com',
messagingSenderId: '677359605826',
appId: '1:677359605826:web:4b349ec0fd147f1d74b5db'
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app); // add this
export { firestore }; // add this
-
Add
firebase
package in your dependency usingnpm i firebase
oryarn add firebase
. -
To add data in
firestore database
, you need to use addDoc method. Here's an example code which stores input data inusers collections
on form submission:
import React, { useState } from 'react';
import { addDoc, collection } from '@firebase/firestore';
import { firestore } from '../firebase'; // your firebase.js directory
export default function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
// reference to users collection in your firestore databse (will be created if not available)
const ref = collection(firestore, 'users');
const handleSubmit = (e) => {
e.preventDefault();
let data = {
name: name,
email: email
};
try {
// add document (data) to referenced (users) collection
addDoc(ref, data);
} catch (err) {
console.log(err);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
required
/>
<input
type="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email address"
required
/>
<button type="submit">Submit</button>
</form>
);
}
Note that firestore
is a NoSQL database. Data are stored as documents
, which are organized into collections
. Document
is basically a JSON object but supports extra data types.
- We're done! You can check and verify the data in your Firebase console in
Firestore
page.