Skip to content

Instantly share code, notes, and snippets.

@erictherobot
Last active February 21, 2022 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erictherobot/3dd624a2749bdc65bfc31dcac739f0ec to your computer and use it in GitHub Desktop.
Save erictherobot/3dd624a2749bdc65bfc31dcac739f0ec to your computer and use it in GitHub Desktop.
Firebase / Firestore version 9 SDK useDocument React Hook
import { useEffect, useState } from 'react';
import { doc, getDoc, DocumentData } from 'firebase/firestore';
import { db } from '@/lib/firebase';
export function useDocument(collection: string, id: string, callback?: any) {
const [data, setData] = useState<DocumentData | undefined>(undefined);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<any>(null);
useEffect(() => {
const getDocument = async () => {
setLoading(true);
try {
const docRef = doc(db, collection, id);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
setData(docSnap.data());
} else {
setData(undefined);
console.log('No document!');
}
} catch (e) {
setError(e.message);
}
setLoading(false);
};
getDocument();
}, [callback]);
return { data, loading, error };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment