Coder Social home page Coder Social logo

kauedm / react-query-firebase Goto Github PK

View Code? Open in Web Editor NEW

This project forked from invertase/react-query-firebase

1.0 0.0 5.0 1.17 MB

React Query hooks for managing asynchronous operations with Firebase. Supports Authentication, Analytics, Firestore & Realtime Database.

Home Page: https://react-query-firebase.invertase.dev

License: Apache License 2.0

JavaScript 1.95% TypeScript 98.05%

react-query-firebase's Introduction

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?

  • Backed by React Query - Unlike other solutions, hooks are built on top of React Query which takes care of complex challenges such as caching, automatic refetching, realtime data subscriptions, pagination & infinite queries, mutations, SSR Support, data selectors, side effect handlers and more. You also get DevTool support out of the box!
  • Un-opinionated - You provide the Query Keys, Configuration & Firebase instances, allowing for full control over how your data is integrated and cached. You can also roll it alongside any existing Firebase usage.
  • Performant & Efficient - Whether your queries are one-off or realtime, the library is designed to be performant and efficient. Data fetching is handled via Queries and Query Keys, meaning components can share data throughout your application without needless database reads.
  • Mutations - Sign a user in, delete a document, run a transaction, log an event... React Query Firebase takes care of that for you via Mutations, allowing you to focus on your application and not managing complex local loading & error states.
  • Fully Typed - The library is built with and has full compatibility with TypeScript.

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.

react-query-firebase's People

Contributors

ehesp avatar cabljac avatar salakar avatar kauedm avatar amonlibanio avatar bvangraafeiland avatar jbethuel avatar eric013 avatar dackers86 avatar vomchik avatar

Stargazers

Roman avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.