Skip to content

Instantly share code, notes, and snippets.

@jamesmurdza
Created August 29, 2023 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmurdza/1948299751d2ddc22a74f0838f4e7e8b to your computer and use it in GitHub Desktop.
Save jamesmurdza/1948299751d2ddc22a74f0838f4e7e8b to your computer and use it in GitHub Desktop.
Firebase and Clerk example hook
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAuth, signInWithCustomToken } from "firebase/auth";
import { firebaseConfig } from "../config/firebase"
import { useAuth } from "@clerk/clerk-react";
import { useEffect, useState } from "react";
// Initialize Firebase app with the provided configuration
const app = initializeApp(firebaseConfig);
// Custom hook to fetch details from Firebase Firestore
export const useDetails = () => {
const [details, setDetails] = useState<any[]>([]);
const [error, setError] = useState(null);
const { getToken } = useAuth(); // Clerk authentication hook
const db = getFirestore(app); // Firestore database instance
const auth = getAuth(app); // Firebase authentication instance
useEffect(() => {
// Function to retrieve details from Firestore
const retrieveDetails = async function () {
try {
// Get the Firebase token from Clerk authentication
const firebaseToken = await getToken({ template: "integration_firebase" });
if (firebaseToken) {
// Sign in to Firebase using the custom token
await signInWithCustomToken(auth, firebaseToken);
// Fetch details from the "example" collection in Firestore
const example = await getDocs(collection(db, "example"));
setDetails(example.docs.map(detail => detail.data()));
}
} catch (err: any) {
// Handle any errors that occur during the retrieval process
setError(err);
};
}
// Call the retrieveDetails function when the component mounts
retrieveDetails();
}, []);
// Return the fetched details and error state
return { details, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment