### Install React Firebase Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/README.md Installs the react-firebase-hooks library using npm or yarn. This requires Node.js and a package manager like npm or yarn. ```bash # with npm npm install --save react-firebase-hooks ``` ```bash # with yarn yarn add react-firebase-hooks ``` -------------------------------- ### useList Hook Full Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md A comprehensive example demonstrating the usage of the `useList` hook to fetch and display data from a Firebase Realtime Database list, including handling loading and error states. ```javascript import { ref, getDatabase } from 'firebase/database'; import { useList } from 'react-firebase-hooks/database'; const database = getDatabase(firebaseApp); const DatabaseList = () => { const [snapshots, loading, error] = useList(ref(database, 'list')); return (

{error && Error: {error}} {loading && List: Loading...} {!loading && snapshots && ( List:{' '} {snapshots.map((v) => ( {v.val()}, ))} )}

); }; ``` -------------------------------- ### useToken Full Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/messaging/README.md A complete React component example demonstrating the `useToken` hook. It initializes the Firebase Messaging instance, calls `useToken`, and conditionally renders error, loading, or token states. ```javascript import { getMessaging } from 'firebase/messaging'; import { useToken } from 'react-firebase-hooks/messaging'; const MessagingToken = () => { const [token, loading, error] = useToken(getMessaging(firebaseApp)); return (

{error && Error: {JSON.stringify(error)}} {loading && Loading token...} {token && Token:{token}}

); }; ``` -------------------------------- ### Full example of useDocument hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md This example demonstrates how to use the `useDocument` hook to fetch and display data from a specific Firestore document, including handling loading and error states. ```js import { getFirestore, doc } from 'firebase/firestore'; import { useDocument } from 'react-firebase-hooks/firestore'; const FirestoreDocument = () => { const [value, loading, error] = useDocument( doc(getFirestore(firebaseApp), 'hooks', 'nBShXiRGFAhuiPfBaGpt'), { snapshotListenOptions: { includeMetadataChanges: true }, } ); return (

{error && Error: {JSON.stringify(error)}} {loading && Document: Loading...} {value && Document: {JSON.stringify(value.data())}}

); }; ``` -------------------------------- ### useObject Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Demonstrates fetching a single object from Firebase Realtime Database using the useObject hook. It shows how to handle loading states, errors, and display the snapshot value. ```javascript import { ref, getDatabase } from 'firebase/database'; import { useObject } from 'react-firebase-hooks/database'; const database = getDatabase(firebaseApp); const DatabaseValue = () => { const [snapshot, loading, error] = useObject(ref(database, 'value')); return (

{error && Error: {error}} {loading && Value: Loading...} {snapshot && Value: {snapshot.val()}}

); }; ``` -------------------------------- ### useCollection Hook Full Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md A complete example demonstrating the usage of the `useCollection` hook in a React component. It shows how to fetch collection data, handle loading states, and display errors. ```javascript import { getFirestore, collection } from 'firebase/firestore'; import { useCollection } from 'react-firebase-hooks/firestore'; const FirestoreCollection = () => { const [value, loading, error] = useCollection( collection(getFirestore(firebaseApp), 'hooks'), { snapshotListenOptions: { includeMetadataChanges: true }, } ); return (

{error && Error: {JSON.stringify(error)}} {loading && Collection: Loading...} {value && ( Collection:{' '} {value.docs.map((doc) => ( {JSON.stringify(doc.data())},{' '} ))} )}

); }; ``` -------------------------------- ### Firebase Auth: Create User Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Demonstrates using the `useCreateUserWithEmailAndPassword` hook to register new users. It handles input for email and password, displays loading states, and shows error messages or the registered user's email upon successful creation. ```jsx import React, { useState } from 'react'; import { useCreateUserWithEmailAndPassword } from 'react-firebase-hooks/auth'; // Assuming auth is initialized elsewhere // const auth = getAuth(firebaseApp); const SignIn = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [createUserWithEmailAndPassword, user, loading, error] = useCreateUserWithEmailAndPassword(auth); if (error) { return (

Error: {error.message}

); } if (loading) { return

Loading...

; } if (user) { return (

Registered User: {user.user.email}

); } return (
setEmail(e.target.value)} placeholder="Email" /> setPassword(e.target.value)} placeholder="Password" />
); }; ``` -------------------------------- ### Social Login Example with useSignInWithXXX Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Demonstrates a basic social login flow using the useSignInWithXXX hook from react-firebase-hooks. It handles loading states, errors, and displays user information upon successful sign-in. ```jsx import { useSignInWithXXX } from 'react-firebase-hooks/auth'; const SignIn = () => { const [signInWithXXX, user, loading, error] = useSignInWithXXX(auth); if (error) { return (

Error: {error.message}

); } if (loading) { return

Loading...

; } if (user) { return (

Signed In User: {user.email}

); } return (
setEmail(e.target.value)} /> setPassword(e.target.value)} />
); }; ``` -------------------------------- ### Firebase Auth: User Login/Logout Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Demonstrates how to use the `useIdToken` hook from `react-firebase-hooks/auth` to manage user authentication state. It includes handling loading, errors, and conditional rendering for logged-in users, login buttons, and logout buttons. ```javascript import { getAuth, signInWithEmailAndPassword, signOut } from 'firebase/auth'; import { useIdToken } from 'react-firebase-hooks/auth'; // Assuming firebaseApp is initialized elsewhere // const firebaseApp = initializeApp(firebaseConfig); const auth = getAuth(firebaseApp); const login = () => { signInWithEmailAndPassword(auth, 'test@test.com', 'password'); }; const logout = () => { signOut(auth); }; const CurrentUser = () => { const [user, loading, error] = useIdToken(auth); if (loading) { return (

Initialising User...

); } if (error) { return (

Error: {error.message}

); } if (user) { return (

Current User: {user.user.email}

); } return ; }; ``` -------------------------------- ### Full Example: Email/Password Sign In with React Firebase Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Demonstrates a complete React component for handling user sign-in using email and password with Firebase authentication. It utilizes the `useSignInWithEmailAndPassword` hook to manage the sign-in process, including loading states, errors, and user data. ```jsx import React, { useState } from 'react'; import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth'; import { auth } from './firebaseConfig'; // Assuming firebase config is in firebaseConfig.js const SignIn = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [ signInWithEmailAndPassword, user, loading, error, ] = useSignInWithEmailAndPassword(auth); if (error) { return (

Error: {error.message}

); } if (loading) { return

Loading...

; } if (user) { return (

Signed In User: {user.email}

); } return (
setEmail(e.target.value)} placeholder="Email" /> setPassword(e.target.value)} placeholder="Password" />
); }; export default SignIn; ``` -------------------------------- ### useObjectVal and useListVals with Transform Example Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Provides a practical example of using the 'transform' option with useObjectVal and useListVals to handle data types not natively supported by Firebase, such as Date objects. It defines a SaleType and applies transformations for date parsing and key/ref field population. ```typescript type SaleType = { idSale: string, date: Date, // <== it is declared as type Date which Firebase does not support. // ...Other fields }; const options = { keyField: 'idSale', transform: (val) => ({ ...val, date: new Date(val.date), }), }; export const useSale: ( idSale: string ) => [SaleType | undefined, boolean, any] = (idSale) => useObjectVal < SaleType > (database.ref(`sales/${idSale}`), options); export const useSales: () => [SaleType[] | undefined, boolean, any] = () => useListVals < SaleType > (database.ref('sales'), options); ``` -------------------------------- ### useCollectionOnce Hook API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md Retrieves the current value of a Firestore Query without setting up a real-time listener. It returns the snapshot, loading state, errors, and a reload function. It accepts a query and optional get options. ```APIDOC useCollectionOnce(query, options) - Retrieves the current value of the `firestore.Query`. - Parameters: - query: (optional) `firestore.Query` for the data you would like to load. - options: (optional) `Object` with the following parameters: - getOptions: (optional) `Object` to customise how the collection is loaded - source: (optional): `'default' | 'server' | 'cache'` Describes whether we should get from server or cache. - Returns: - snapshot: a `firestore.QuerySnapshot`, or `undefined` if no query is supplied. - loading: a `boolean` to indicate if the data is still being loaded. - error: Any `firestore.FirestoreError` returned by Firebase when trying to load the data, or `undefined` if there is no error. - reload(): a function that can be called to trigger a reload of the data. ``` -------------------------------- ### Get collection data once with React Firebase Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md The `useCollectionDataOnce` hook fetches a collection of documents from Firestore a single time, returning a typed list of document values. It accepts a Firestore query and options, including source preference ('default', 'server', 'cache'), and provides data, loading state, error, snapshot, and a reload function. ```js const [values, loading, error, snapshot] = useCollectionDataOnce < T > (query, options); ``` -------------------------------- ### Get typed collection data with React Firebase Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md The `useCollectionData` hook fetches and monitors a collection of documents from Firestore, returning a typed list of document values. It takes a Firestore query and optional options for customization, providing data, loading state, error information, and the raw snapshot. ```js const [values, loading, error, snapshot] = useCollectionData < T > (query, options); ``` -------------------------------- ### Import Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Demonstrates how to import the necessary hooks from the react-firebase-hooks/database package. ```javascript import { useList } from 'react-firebase-hooks/database'; ``` -------------------------------- ### useSignInWithApple: React Firebase Hook for Apple Authentication Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Provides a hook for signing users in with their Apple account. It wraps the underlying Firebase `auth.signInWithPopup` method using an `OAuthProvider` and offers convenient `user`, `loading`, and `error` states. The hook requires an `Auth` instance. ```js const [signInWithApple, user, loading, error] = useSignInWithApple(auth); // Parameters: // auth: Auth instance for the app. // Returns: // signInWithApple: Function to initiate Apple login. Accepts optional scopes and custom OAuth parameters. // - Returns Promise on success, undefined on error. // user: auth.UserCredential if logged in, undefined otherwise. // loading: Boolean indicating if the login process is ongoing. // error: Firebase Error object or undefined. ``` -------------------------------- ### Import useCollection Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md Demonstrates how to import the `useCollection` hook from the react-firebase-hooks/firestore package. This is the primary way to access the hook for real-time collection data. ```javascript import { useCollection } from 'react-firebase-hooks/firestore'; ``` -------------------------------- ### Use Download URL Hook for Firebase Storage Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/storage/README.md Retrieves the download URL for a Firebase Storage reference. It provides loading and error states for a complete lifecycle management. Requires a Firebase Storage reference as input. ```javascript import { useDownloadURL } from 'react-firebase-hooks/storage'; ``` ```jsx import { getStorage, ref as storageRef } from 'firebase/storage'; import { useDownloadURL } from 'react-firebase-hooks/storage'; // Assume firebaseApp is initialized const storage = getStorage(firebaseApp); const DownloadURLComponent = () => { // The hook takes a storage reference const [downloadUrl, loading, error] = useDownloadURL(storageRef(storage, 'path/to/your/file.jpg')); return (
{error && Error: {error.message}} {loading && Loading download URL...} {!loading && downloadUrl && (

Download URL: {downloadUrl}

)}
); }; ``` -------------------------------- ### useSignInWithGithub: React Firebase Hook for GitHub Authentication Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Facilitates user authentication via GitHub accounts. This hook leverages Firebase's `auth.signInWithPopup` with the `OAuthProvider` for GitHub, providing a streamlined interface. It returns the user's credential, a loading indicator, and error information. ```js const [signInWithGithub, user, loading, error] = useSignInWithGithub(auth); // Parameters: // auth: Auth instance for the app. // Returns: // signInWithGithub: Function to initiate GitHub login. Accepts optional scopes and custom OAuth parameters. // - Returns Promise on success, undefined on error. // user: auth.UserCredential if logged in, undefined otherwise. // loading: Boolean indicating if the login process is ongoing. // error: Firebase Error object or undefined. ``` -------------------------------- ### useSignInWithEmailLink Hook API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md API documentation for the useSignInWithEmailLink hook, used to log in a user with an email and a sign-in email link. It wraps the auth.signInWithEmailLink method and provides loading and error states. ```APIDOC useSignInWithEmailLink(auth) - Login a user using an email and sign-in email link. - Wraps the underlying `auth.signInWithEmailLink` method and provides additional `loading` and `error` information. Parameters: - auth: `Auth` instance for the app you would like to monitor Returns: - signInWithEmailLink(email: string, emailLink?: string) => Promise: - A function you can call to start the login. - If no `emailLink` is supplied, the link is inferred from the current URL. - Returns the `auth.UserCredential` if the user was signed in successfully, or `undefined` if there was an error. - user: The `auth.UserCredential` if the user was logged in or `undefined` if not - loading: A `boolean` to indicate whether the the user login is processing - error: Any `Error` returned by Firebase when trying to login the user, or `undefined` if there is no error ``` -------------------------------- ### useCreateUserWithEmailAndPassword API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Provides a hook for creating new users with email and password in Firebase Authentication. It wraps the underlying `createUserWithEmailAndPassword` method, offering loading and error states. Supports optional email verification settings. ```APIDOC useCreateUserWithEmailAndPassword(auth, options?) - Creates a user with email and password. - Wraps the underlying `firebase.auth().createUserWithEmailAndPassword` method. - Provides additional `loading` and `error` information. Parameters: - auth: `auth.Auth` instance for the app you would like to monitor. - options: (optional) `Object` with the following parameters: - emailVerificationOptions: (optional) `auth.ActionCodeSettings` to customise the email verification. - sendEmailVerification: (optional) `boolean` to trigger sending of an email verification after the user has been created. Returns: - createUserWithEmailAndPassword(email: string, password: string) => Promise: A function you can call to start the registration. Returns the `auth.UserCredential` if the user was created successfully, or `undefined` if there was an error. - user: The `auth.UserCredential` if the user was created or `undefined` if not. - loading: A `boolean` to indicate whether the user creation is processing. - error: Any `Error` returned by Firebase when trying to create the user, or `undefined` if there is no error. ``` -------------------------------- ### useSendSignInLinkToEmail Hook API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md API documentation for the useSendSignInLinkToEmail hook, which sends a sign-in email link to a user. It wraps the underlying Firebase auth method and provides loading and error states. ```APIDOC useSendSignInLinkToEmail(auth) - Sends a sign-in email link to the user with the specified email. - Wraps the underlying `auth.sendSignInLinkToEmail` method and provides additional `sending` and `error` information. - To complete sign in with the email link use the [useSignInWithEmailLink](#usesigninwithemaillink) hook. Parameters: - auth: `Auth` instance for the app you would like to monitor Returns: - sendSignInLinkToEmail(email: string, actionCodeSettings: ActionCodeSettings) => Promise: - A function you can call to send a sign-in email link to an email. - Requires an [actionCodeSettings](https://firebase.google.com/docs/reference/js/auth.actioncodesettings.md#actioncodesettings_interface) object. - Returns `true` if the function was successful, or `false` if there was an error. - sending: A `boolean` to indicate whether the email is being sent - error: Any `Error` returned by Firebase when trying to send the email, or `undefined` if there is no error Full Example: ```jsx import { useSendSignInLinkToEmail } from 'react-firebase-hooks/auth'; const SendSignInLinkToEmail = () => { const [email, setEmail] = useState(''); const [sendSignInLinkToEmail, sending, error] = useSendSignInLinkToEmail( auth ); const actionCodeSettings = { // The URL to redirect to for sign-in completion. This is also the deep // link for mobile redirects. The domain (www.example.com) for this URL // must be whitelisted in the Firebase Console. url: 'https://www.example.com/finishSignUp?cartId=1234', iOS: { bundleId: 'com.example.ios', }, android: { packageName: 'com.example.android', installApp: true, minimumVersion: '12', }, // This must be true. handleCodeInApp: true, }; if (error) { return (

Error: {error.message}

); } if (sending) { return

Sending...

; } return (
setEmail(e.target.value)} />
); }; ``` ``` -------------------------------- ### useSignInWithGoogle Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Facilitates user login using Google Authentication within a React application. It wraps Firebase's `auth.signInWithPopup` with `auth.GoogleProvider` and provides convenient state management for loading and errors. Requires an initialized Firebase `Auth` instance. ```javascript const [signInWithGoogle, user, loading, error] = useSignInWithGoogle(auth); ``` -------------------------------- ### useListKeys Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Similar to `useList`, this hook extracts only the keys from a list of database snapshots. It takes a reference and returns an array of keys, a loading boolean, and an error object. ```javascript const [keys, loading, error] = useListKeys(reference); ``` -------------------------------- ### useObjectVal Hook API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Details the useObjectVal hook, which returns the typed contents of a database.DataSnapshot.val() directly, simplifying data access compared to useObject. It outlines parameters like reference and options (keyField, refField, transform). ```APIDOC useObjectVal (reference, options) Parameters: - reference: (optional) database.Reference for the data you would like to load. - options: (optional) Object with the following parameters: - keyField: (optional) string field name that should be populated with the database.DataSnapshot.key property in the returned value. - refField: (optional) string field name that should be populated with the database.DataSnapshot.ref property. - transform: (optional) a function that receives the raw database.DataSnapshot.val() to allow manual transformation of the data. Returns: - value: a T, or undefined if no reference is supplied. - loading: a boolean to indicate if the data is still being loaded. - error: Any FirebaseError returned by Firebase when trying to load the data, or undefined if there is no error. ``` -------------------------------- ### useList Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Retrieves and monitors a list value in the Firebase Realtime Database. It takes a database reference and returns an array of snapshots, a loading boolean, and an error object. ```javascript const [snapshots, loading, error] = useList(reference); ``` -------------------------------- ### useSignInWithYahoo Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Integrates Yahoo Authentication for user login within React applications using Firebase. The hook wraps Firebase's `auth.signInWithPopup` and `auth.OAuthProvider`, simplifying the management of `user`, `loading`, and `error` states. A Firebase `Auth` instance is a prerequisite. ```javascript const [signInWithYahoo, user, loading, error] = useSignInWithYahoo(auth); ``` -------------------------------- ### useSignInWithFacebook: React Firebase Hook for Facebook Authentication Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Enables user sign-in using Facebook credentials. This hook simplifies the process by abstracting Firebase's `auth.signInWithPopup` with the `OAuthProvider` for Facebook. It returns the user credential, loading status, and any potential errors. ```js const [signInWithFacebook, user, loading, error] = useSignInWithFacebook(auth); // Parameters: // auth: Auth instance for the app. // Returns: // signInWithFacebook: Function to initiate Facebook login. Accepts optional scopes and custom OAuth parameters. // - Returns Promise on success, undefined on error. // user: auth.UserCredential if logged in, undefined otherwise. // loading: Boolean indicating if the login process is ongoing. // error: Firebase Error object or undefined. ``` -------------------------------- ### Sign In with Email Link using useSignInWithEmailLink Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Demonstrates how to use the `useSignInWithEmailLink` hook from react-firebase-hooks to sign users into Firebase using an email link. It handles loading states, errors, and displays the signed-in user's email. ```jsx import { useSignInWithEmailLink } from 'react-firebase-hooks/auth'; const SignIn = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [ signInWithEmailLink, user, loading, error, ] = useSignInWithEmailLink(auth); if (error) { return (

Error: {error.message}

); } if (loading) { return

Loading...

; } if (user) { return (

Signed In User: {user.email}

); } return (
setEmail(e.target.value)} /> setPassword(e.target.value)} />
); }; ``` -------------------------------- ### useSignInWithEmailAndPassword API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Provides a hook for signing in users with email and password in Firebase Authentication. It wraps the `auth.signInWithEmailAndPassword` method, offering loading and error states. This hook simplifies the process of handling user login flows. ```APIDOC useSignInWithEmailAndPassword(auth) - Logs in a user with email and password. - Wraps the underlying `auth.signInWithEmailAndPassword` method. - Provides additional `loading` and `error` information. Parameters: - auth: `Auth` instance for the app you would like to monitor. Returns: - signInWithEmailAndPassword(email: string, password: string) => Promise: A function you can call to start the login. Returns the `auth.UserCredential` if the user was signed in successfully, or `undefined` if there was an error. - user: The `auth.UserCredential` if the user was logged in or `undefined` if not. - loading: A `boolean` to indicate whether the user login is processing. - error: Any `Error` returned by Firebase when trying to login the user, or `undefined` if there is no error. ``` -------------------------------- ### Use Upload File Hook for Firebase Storage Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/storage/README.md Facilitates uploading files to Firebase Storage. It returns a function to initiate uploads, along with states for uploading progress, snapshots, and errors. Accepts a storage reference, file, and optional metadata. ```javascript import { useUploadFile } from 'react-firebase-hooks/storage'; ``` ```jsx import { getStorage, ref as storageRef } from 'firebase/storage'; import { useUploadFile } from 'react-firebase-hooks/storage'; import React, { useState } from 'react'; // Assume firebaseApp is initialized const storage = getStorage(firebaseApp); const UploadFileComponent = () => { // The hook returns an upload function, uploading state, snapshot, and error const [uploadFile, uploading, snapshot, error] = useUploadFile(); const [selectedFile, setSelectedFile] = useState(null); const fileRef = storageRef(storage, 'uploads/my-file.jpg'); const handleFileChange = (event) => { if (event.target.files && event.target.files[0]) { setSelectedFile(event.target.files[0]); } }; const handleUpload = async () => { if (selectedFile) { try { // Call the upload function with reference, file, and metadata const result = await uploadFile(fileRef, selectedFile, { contentType: 'image/jpeg' }); alert(`Upload successful: ${JSON.stringify(result)}`); } catch (uploadError) { console.error('Upload failed:', uploadError); } } }; return (
{error &&

Error: {error.message}

} {snapshot &&

Upload Progress: {snapshot.bytesTransferred} / {snapshot.totalBytes}

}
); }; ``` -------------------------------- ### useSignInWithMicrosoft Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Enables user login via Microsoft Authentication in React applications. This hook utilizes Firebase's `auth.signInWithPopup` with `auth.OAuthProvider` and exposes `user`, `loading`, and `error` states. An active Firebase `Auth` instance is necessary. ```javascript const [signInWithMicrosoft, user, loading, error] = useSignInWithMicrosoft(auth); ``` -------------------------------- ### useObject Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Retrieves and monitors a single object or primitive value from the Firebase Realtime Database. It takes a reference and returns a single snapshot, a loading boolean, and an error object. ```javascript const [snapshot, loading, error] = useObject(reference); ``` -------------------------------- ### Monitor document data with React Firebase Hooks Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md The `useDocument` hook retrieves and monitors a single document from Cloud Firestore, returning the document snapshot, loading status, and any errors. It takes a Firestore document reference and optional snapshot listen options. ```js const [snapshot, loading, error] = useDocument(reference, options); ``` -------------------------------- ### useHttpsCallable Hook for Firebase Cloud Functions Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/functions/README.md The `useHttpsCallable` hook simplifies calling Firebase Cloud Functions. It takes a Firebase `functions` instance and the function `name` as arguments. It returns an `executeCallable` function, a `loading` boolean, and an `error` object to manage the function execution lifecycle. ```javascript import { useHttpsCallable } from 'react-firebase-hooks/functions'; ``` ```javascript const [executeCallable, loading, error] = useHttpsCallable(functions, name); ``` ```javascript import { getFunctions } from 'firebase/functions'; import { useHttpsCallable } from 'react-firebase-hooks/functions'; const HttpsCallable = () => { const [executeCallable, executing, error] = useHttpsCallable( getFunctions(firebaseApp), 'myHttpsCallable' ); return (

{error && Error: {JSON.stringify(error)}} {executing && Function executing...}

); }; ``` -------------------------------- ### useToken Hook Signature Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/messaging/README.md The `useToken` hook retrieves a Firebase Cloud Messaging token. It takes a Firebase Messaging instance and an optional VAPID key. It returns the token, a loading state, and any potential error. ```javascript const [token, loading, error] = useToken(messaging, vapidKey); ``` -------------------------------- ### Transforming Data with useObjectVal and useListVals Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md Explains the 'transform' option for useObjectVal and useListVals hooks, allowing custom data type conversions (e.g., string to Date) or restructuring. It details the transform function signature and best practices like memoization. ```javascript transform?: (val: any) => T; // Example usage with type casting and custom logic: transform: ({ firstName, lastName, someBool, ...val }) => ({ // Merge in default values, declared elsewhere: ...defaultValues, // Override them with the actual values ...val, // Create new fields from existing values fullName: `${firstName} ${lastName}`, // Ensure a field is a proper boolean instead of truish or falsy: someBool: !!someBool, // Same goes for any other poorly represented data type }); ``` -------------------------------- ### useCollection Hook API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md Provides and monitors a collection value in Cloud Firestore. It returns the snapshot, loading state, and any errors encountered. It accepts a Firestore query and optional listen options. ```APIDOC useCollection(query, options) - Retrieves and monitors a collection value in Cloud Firestore. - Parameters: - query: (optional) `firestore.Query` for the data you would like to load. - options: (optional) `Object` with the following parameters: - snapshotListenOptions: (optional) `firestore.SnapshotListenOptions` to customise how the query is loaded. - Returns: - snapshot: a `firestore.QuerySnapshot`, or `undefined` if no query is supplied. - loading: a `boolean` to indicate if the data is still being loaded. - error: Any `firestore.FirestoreError` returned by Firebase when trying to load the data, or `undefined` if there is no error. ``` -------------------------------- ### useListVals Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/database/README.md This hook extracts the values from a list of database snapshots, allowing for optional transformations and mapping of key/ref fields. It takes a reference and options, returning typed values, a loading boolean, and an error object. ```javascript const [values, loading, error] = useListVals (reference, options); ``` -------------------------------- ### Update User Profile with useUpdateProfile Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md The `useUpdateProfile` hook from `react-firebase-hooks/auth` simplifies updating a user's display name and photo URL. It wraps the underlying `auth.updateProfile` method, providing `updating` and `error` states. The hook takes an `Auth` instance and returns a function to update the profile, a boolean for the updating state, and any error encountered. ```jsx import React, { useState } from 'react'; import { useUpdateProfile } from 'react-firebase-hooks/auth'; import { auth } from './firebase'; // Assuming firebase auth is initialized elsewhere const UpdateProfile = () => { const [displayName, setDisplayName] = useState(''); const [photoURL, setPhotoURL] = useState(''); const [updateProfile, updating, error] = useUpdateProfile(auth); if (error) { return (

Error: {error.message}

); } if (updating) { return

Updating...

; } return (
setDisplayName(e.target.value)} /> setPhotoURL(e.target.value)} />
); }; export default UpdateProfile; ``` -------------------------------- ### Verify and Update Email with useVerifyBeforeUpdateEmail Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md The `useVerifyBeforeUpdateEmail` hook from `react-firebase-hooks/auth` handles the process of verifying and updating a user's email address. It wraps the `auth.verifyBeforeUpdateEmail` method, providing `updating` and `error` states. The hook accepts an `Auth` instance and returns a function to perform the verification, a boolean indicating the update process, and any error that occurs. ```js const [verifyBeforeUpdateEmail, updating, error] = useVerifyBeforeUpdateEmail( auth ); ``` ```jsx import React, { useState } from 'react'; import { useVerifyBeforeUpdateEmail } from 'react-firebase-hooks/auth'; import { auth } from './firebase'; // Assuming firebase auth is initialized elsewhere const VerifyBeforeUpdateEmail = () => { const [email, setEmail] = useState(''); const [verifyBeforeUpdateEmail, updating, error] = useVerifyBeforeUpdateEmail( auth ); if (error) { return (

Error: {error.message}

); } if (updating) { return

Updating...

; } return (
setEmail(e.target.value)} />
); }; export default VerifyBeforeUpdateEmail; ``` -------------------------------- ### Sign Out User with useSignOut Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Signs out the current user, wrapping the underlying `auth.signOut` method. It provides `loading` and `error` states for managing the sign-out process. The hook takes an `Auth` instance and returns a function to trigger the sign-out, a boolean indicating if the process is ongoing, and any error encountered. ```javascript const [signOut, loading, error] = useSignOut(auth); ``` ```jsx import { useSignOut } from 'react-firebase-hooks/auth'; const SignOut = () => { const [signOut, loading, error] = useSignOut(auth); if (error) { return (

Error: {error.message}

); } if (loading) { return

Loading...

; } return (
); }; ``` -------------------------------- ### useSignInWithTwitter Hook Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Provides functionality to log in users with Twitter Authentication using React Firebase Hooks. It abstracts Firebase's `auth.signInWithPopup` and `auth.OAuthProvider`, offering clear `user`, `loading`, and `error` states. The hook requires a Firebase `Auth` instance. ```javascript const [signInWithTwitter, user, loading, error] = useSignInWithTwitter(auth); ``` -------------------------------- ### Firestore Data Conversion API Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md Describes the Firestore DataConverter API for transforming data as it leaves Firestore and accessing underlying `id` and `ref` fields. This replaces older options like `transform`, `idField`, and `refField` from previous library versions. ```APIDOC FirestoreDataConverter: Purpose: Transform data as it leaves Firestore, access id and ref fields. Reference: https://firebase.google.com/docs/reference/js/firestore_.firestoredataconverter Usage: Implemented by creating an object with `toFirestore` and `fromFirestore` methods. `toFirestore(data, options)`: Converts a JavaScript object to a Firestore document. `fromFirestore(snapshot, options)`: Converts a Firestore document snapshot to a JavaScript object. Note: Replaces v4 options like `transform`, `idField`, `refField`. ``` -------------------------------- ### Monitor Firebase ID Token Changes with useIdToken Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/auth/README.md Retrieve and monitor changes to the Firebase ID token using the `useIdToken` hook. This hook utilizes `auth.onIdTokenChanged` and captures sign-in, sign-out, and token refresh events. It returns the user object, a loading state, and any potential errors. ```javascript const [user, loading, error] = useIdToken(auth, options); ``` -------------------------------- ### Retrieve Document Once (useDocumentOnce Hook) Source: https://github.com/csfrequency/react-firebase-hooks/blob/master/firestore/README.md Fetches the current value of a Firestore DocumentReference. It returns the snapshot, loading state, error, and a reload function. The hook takes an optional reference and options for customizing data fetching. ```javascript const [snapshot, loading, error, reload] = useDocumentOnce(reference, options); ```