invertase / tanstack-query-firebase

React Query hooks for managing asynchronous operations with Firebase. Supports Authentication, Analytics, Firestore & Realtime Database.
https://react-query-firebase.invertase.dev
Apache License 2.0
393 stars 70 forks source link
analytics authentication database firebase firebase-auth firestore functions hacktoberfest react react-hooks react-query reactjs realtime-database

[!IMPORTANT]
This project is currently undergoing a overhaul, to support TanStack v5 - this includes a package restructuring, and enables support for other web frameworks!

React Query Firebase

A set of React Query hooks integrating with Firebase.

Installation DocumentationLicense


React Query Firebase provides a set of easy to use hooks for handling asynchronous tasks with Firebase in your React application.

Why should I use React Query Firebase?

Note: The library supports the Firebase JS SDK v9 - learn more about it here!

Example

As an example, let's use a Firestore hooks to fetch a document & run a transaction whilst easily handling asynchronous state.

import {
  useFirestoreDocument,
  useFirestoreTransaction,
} from "@react-query-firebase/firestore";
import { doc } from "firebase/firestore";
import { firestore } from "./config/firebase";

type Product = {
  name: string;
  price: number;
};

function ProductPage({ id }: { id: string }) {
  // Create a Firestore document reference
  const ref = doc(firestore, "products", id);

  // Query a Firestore document using useQuery
  const product = useFirestoreDocument<Product>(
    ["product", id],
    ref,
    {
      // Subscribe to realtime changes
      subscribe: true,
      // Include metadata changes in the updates
      includeMetadataChanges: true,
    },
    {
      // Optionally handle side effects with React Query hook options
      onSuccess(snapshot) {
        console.log("Successfully fetched product ID: ", snapshot.id);
      },
    }
  );

  // Run a Firestore transaction as Mutation using useMutation
  const like = useFirestoreTransaction(
    auth,
    async (tsx) => {
      const record = await tsx.get(ref);
      tsx.update(ref, {
        likes: record.data().likes + 1,
      });
    },
    {
      onError(error) {
        console.error("Failed to like product!", error);
      },
    }
  );

  if (product.isLoading) {
    return <div>Loading...</div>;
  }

  if (product.isError) {
    return <div>Failed to fetch product: {product.error.message}</div>;
  }

  const snapshot = product.data; // DocumentSnapshot<Product>

  return (
    <div>
      <h1>{snapshot.data().name}</h1>
      <button disabled={like.isLoading} onClick={() => like.mutate()}>
        Like Product!
      </button>
      {like.isError && <p>Failed to like product: {like.error.message}</p>}
    </div>
  );
}

Installation

If you haven't done so already, install react, react-query & firebase (v9):

npm i --save react react-query firebase

Before using this library, ensure React Query is setup on your project by following the Installation guide.

Next install one of the React Query Firebase packages, e.g:

npm i --save @react-query-firebase/firestore

See below for a full list of available packages.

Packages

License


Built and maintained by Invertase.