
Firebase
Table of contents
Open Table of contents
Configuration
Install
npm i firebase
Create Project
Create a project by visiting this link
Firebase Config file
Go to Project Overview -> Project setting and copy the config to Firebase/Firebase-config.js
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "AIzaS...",
authDomain: "sho...",
projectId: "sho...",
storageBucket: "sho...",
messagingSenderId: "981...",
appId: "1:98...",
};
export const FirebaseApp = initializeApp(firebaseConfig); /* export this */
Sign In
How to use
In order to use firebase we first need to import exported firebase config and few other things
import { FirebaseApp } from "somewhere/Firebase/Firebase-config.js";
import {
getAuth,
onAuthStateChanged,
signInWithPopup,
signInWithRedirect,
getRedirectResult,
GoogleAuthProvider,
signOut,
} from "firebase/auth";
Initialize app and provider
Out side the component
const auth = getAuth(FirebaseApp);
const GoogleProvider = new GoogleAuthProvider();
… Other providers can also be initialized similarly… check Facebook Microsoft
Auth state
Recommended component
put this outside if used raw but i higly advise to use the callback version which goes inside useEffect. There is one more benifit of using callback version and that is we call manage states without needing localhost
Raw version
onAuthStateChanged(auth, user => {
if (user) {
const uid = user.uid;
// Do something
console.log({ uid });
// ...
} else {
// User is signed out
// ...
}
});
Callback version
const observer = callback => {
onAuthStateChanged(auth, callback);
};
useEffect(() => {
const callbackFunction = user => {
console.log("this function runs whenever auth changes", user);
};
const unsubscribe = observer(callbackFunction);
return unsubscribe;
}, []);
Sigin with redirect(recommended)
const signInHandler = () => {
signInWithRedirect(auth, GoogleProvider);
};
If we use redirect then we also need to have getRedirectResult or have auth state checked with onAuthStateChanged
Out side the component or within useEffect in the later case you can use hook(useNavigate) to redirect to homepage after successful login
getRedirectResult(auth)
.then(result => {
// This gives you a Google Access Token. You can use it to access Google APIs.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
console.log({ user, token });
redirect("/");
})
.catch(error => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error?.message;
// The email of the user's account used.
const email = error.customData?.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
console.log({ errorCode, errorMessage, email, credential });
});
Sigin In with popup
signInWithPopup(auth, GoogleProvider)
.then(result => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
})
.catch(error => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
SiginOut user
const signOutUser = () => {
signOut(auth)
.then(() => {
// Sign-out successful.
console.log("sigin out successful");
})
.catch(error => {
// An error happened.
console.log("encountered error during sigin out ", error);
});
};
Firebase cloud
Initialize
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(FirebaseApp); //const db = getFirestore(app); same thing
This can be initialized in firebase config file or in the file where you want to use cloud db functions
Read data
import { getFirestore, doc, setDoc, getDoc } from "firebase/firestore";
const populateUserInDB = async uid => {
const userRef = doc(db, "users", uid); // reference uid document, containing the data, in "users" collection within database
const userSnap = await getDoc(userRef); // read data from ref object
if (userSnap.exists()) {
//data exist so do something
console.log("Document data:", userSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!, hence creating data");
}
};
Write data
import { doc, setDoc } from "firebase/firestore";
const docRef = doc(db, "cities", "LA");
const data = {
name: "Los Angeles",
state: "CA",
country: "USA",
};
// Add a new document in collection "cities"
await setDoc(docRef, data);
Update data
import { doc, updateDoc } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Set the "capital" field of the city 'DC'
await updateDoc(washingtonRef, {
capital: true,
});