{"id":15566864,"url":"https://github.com/rioam2/usefire","last_synced_at":"2025-04-23T23:48:20.749Z","repository":{"id":37822267,"uuid":"197866186","full_name":"rioam2/useFire","owner":"rioam2","description":"⚓ Declarative React Hooks for quick and easy Firebase/Firestore integration","archived":false,"fork":false,"pushed_at":"2023-01-05T05:51:56.000Z","size":927,"stargazers_count":5,"open_issues_count":36,"forks_count":2,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-23T23:47:48.555Z","etag":null,"topics":["database","firebase","firestore","react","react-hook","real-time"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/usefire","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rioam2.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-07-20T01:56:36.000Z","updated_at":"2020-12-18T16:41:22.000Z","dependencies_parsed_at":"2023-02-03T14:31:00.895Z","dependency_job_id":null,"html_url":"https://github.com/rioam2/useFire","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rioam2%2FuseFire","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rioam2%2FuseFire/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rioam2%2FuseFire/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rioam2%2FuseFire/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rioam2","download_url":"https://codeload.github.com/rioam2/useFire/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250535098,"owners_count":21446505,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","firebase","firestore","react","react-hook","real-time"],"created_at":"2024-10-02T17:07:44.008Z","updated_at":"2025-04-23T23:48:20.693Z","avatar_url":"https://github.com/rioam2.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# useFire\n\n[![Build Status](https://travis-ci.com/rioam2/useFire.svg?branch=master)](https://travis-ci.com/rioam2/useFire)\n[![Coverage Status](https://coveralls.io/repos/github/rioam2/useFire/badge.svg?branch=master)](https://coveralls.io/github/rioam2/useFire?branch=master)\n[![TypeScript](https://badges.frapsoft.com/typescript/version/typescript-next.svg?v=101)](https://github.com/ellerbrock/typescript-badges/)\n[![NPM Version](https://img.shields.io/npm/v/usefire.svg)](https://www.npmjs.com/package/usefire)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://img.shields.io/badge/license-MIT-blue.svg)\n\nDeclarative React Hooks for quick and easy Firebase/Firestore integration.  \n\n# Overview\n\nFirebase has as wonderful API, but it's notoriously difficult to integrate with React because of it's imperative nature. `useFire` aims to eliminate this frustration. For example, using React hooks and `useFire`, we can write clean and declarative code to access real-time data from a Firestore database:\n\n```js\n// ...\n\nconst defaultData = {}; // Default used to initialize document if it doesn't exist.\nconst fallbackData = {}; // Fallback used when not authorized to access resource.\nconst [ data, setData, setDataPerms ] = useFirestore(`/users/1234`, defaultData, fallbackData);\n\n// When an update happens on the database, a re-render will automatically be triggered\n// and `data` will reflect the updates. This all happens real-time. You also get access\n// to dynamic permission management out-of-the-box!\n\n// ...\n```\n\n\nUsually, using only firebase's native APIs, you would need to slew the following imperative code all over your react component to access data in real-time. Because React has put so much focus on eliminating imperative code, this is particularly undesirable...\n\n```js\n// ...\n\n// Access document: /users/\u003cuser-uid\u003e\nconst fallbackData = {};\nconst defaultData = {};\nconst docRef = db.doc(\"users/1234\");\n\ndocRef.onSnapshot(function(snap) {\n    // Document has been updated remotely, sync changes to local state...\n    snap.get().then(function(doc) {\n        const data = doc.data();\n        this.setState(data)\n    }).catch(function() {\n        // Failed to get document, use fallback...\n        this.setState(fallbackData);\n    })\n}, function() {\n    // Snapshot error, use fallback...\n    this.setState(fallbackData);\n});\n\n// ...\n```\n\n# Quick Start\n\nUsing yarn:\n\n`yarn add useFire`\n\nor NPM:\n\n`npm i useFire`\n\n# Usage\n\nThe default export of this package is a factory function that returns the hooks wrapped in an object. This is done so that the resulting hooks can be explicitly bound to your application's React and Firebase instances. Below is the recommended pattern for binding and accessing/re-exporting the hooks from within your app:\n\n```js\n// examples/firebase/hooks.js\n\nimport * as React from 'react';\nimport { useFire } from 'usefire'; // yarn add usefire\nimport FirebaseApp from './app';\n\n// Using authentication and firestore features\nimport 'firebase/firestore';\nimport 'firebase/auth';\n\n// Export hooks bound to your application's React and Firebase instances\nexport const { useFirestore, useFireauth } = useFire(React, FirebaseApp);\n\n```\n\nNow, you will be able to access `useFire` hooks by importing them from your version of the file above.\n\n# API Reference\n\n - #### `useFireauth ()`\n   - Declarative Hook wrapper for Firebase's authentication APIs. The returned hook is an object, because the contents of the hook do not have a clear order of importance.\n   - #### Returned Hook: ` { user, isLoading, login, logout, register } `\n     - `user: firebase.User | null` - The currently logged in firebase user or null\n     - `isLoading: boolean` - True while firebase is initializing after a new page visit or refresh. Validity of the user is not guaranteed until loading is complete.\n     - `login: object`: All of the following are the same as Firebase provides out-of-the-box. See Firebase's official documentation for more details.\n       - `withCredential: (credential: firebase.auth.AuthCredential) =\u003e Promise\u003cfirebase.auth.UserCredential\u003e` \n       - `withEmailAndPassword: (email: string, password: string) =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n       - `withEmailLink: (email: string, emailLink?: string | undefined) =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n       - `withFacebook: () =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n       - `withGithub: () =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n       - `withGoogle: () =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n       - `withToken: (token: string) =\u003e Promise\u003cfirebase.auth.UserCredential\u003e`\n     - `logout: () =\u003e Promise\u003cvoid\u003e` - Logs out the currently signed-in user. If logged out already, this method is a no-op.\n     - `register: object`: Creates a new user with the provided username and password. If successful, the user will be logged in. See Firebase's official documentation for more details.\n       - `withEmailAndPassword: (user: string, password: string) =\u003e Promise\u003cfirebase.auth.UserCredential\u003e` - Th \n\n - #### `useFirestore\u003cT\u003e ( path: string, initialValue: T, fallbackValue: T )`\n   - Hook wrapper for Firestore's native APIs with added support for permission handling, dot-walking, initial and fallback values. Data is bound to Firestore using `DocumentReference.onSnapshot()` for real-time data-linking.\n   - **Parameters:**\n     - **` path: string `** - Path of the document to use. Supports dot-walking to specific document fields or nested maps and '$' as a substitute for `/users/\u003cuser-uid\u003e`.\n       - Example: ` path = '$.favoriteColor' ` accesses the 'favoriteColor' field on the document `/users/\u003cuser-uid\u003e`\n     - **` initialValue: T `** - Used as an initial value if the document or field does not already exist. Must be an object if a document is referenced in the path instead of a specific field.\n     - **` fallbackValue: T `** - Fallback value shown to unauthorized users. If not provided, `initialValue` is used.\n   - #### Returned Hook: ` [ data, setData, setDocPerm ] `\n     - **`data: T`** - real-time document or field data referenced by the provided database path.\n     - **`setData: (newData: T) =\u003e Promise\u003cvoid\u003e`** - sets the data referenced by the provided database path both remotely and locally. Causes a re-render of the enclosing React component.\n     - **`setDocPerm: (uid: string, perms: PermissionMap) =\u003e Promise\u003cvoid\u003e`** - See ['Using Permissions'](#using-permissions) below. Sets document access permissions for the user who's uid is provided. 'perms' should be an object with boolean entries for the `read`, `write`, `get`, `list`, `create`, `update`, and `delete` permissions. The latter 4 more granular permissions will take precedence over the more general permissions `read` and `write` when both present.\n       - **Warning:** This sets permissions for the entire document even if a specific field is referenced by the provided path.\n       - Example: `setDocPerm('1234', { read: true, write: false })` gives read-only access to the user with uid '1234' on the document referenced by the path provided to the hook.\n\n# Using Permissions\n\nThis hook API assumes that you are using an extension of the following basic Firestore rules:\n\n```js\n// examples/firestore.rules\n\nservice cloud.firestore {\n  match /databases/{database}/documents {\n  \n    // Users have access to their own scope\n    match /users/{pathUID} {\n      allow read, write: if pathUID == request.auth.uid;\n    \tmatch /{nested=**} {\n        allow read, write: if pathUID == request.auth.uid;      \n      }\n    }\n    \n    // Default behavior: check permissions map on document\n    match /{defaultSchema=**} {\n      function userCan(perm) { \n        return resource != null \u0026\u0026\n               exists(resource[\"__name__\"]) \u0026\u0026\n               ('permissions') in resource.data \u0026\u0026 \n               resource.data.permissions is map \u0026\u0026\n               (request.auth.uid) in resource.data.permissions \u0026\u0026 \n               resource.data.permissions[request.auth.uid] is map \u0026\u0026\n               (perm) in resource.data.permissions[request.auth.uid] \u0026\u0026 \n               resource.data.permissions[request.auth.uid][perm] is bool \u0026\u0026\n               resource.data.permissions[request.auth.uid][perm]; \n      }\n      allow get: if userCan('get');\n      allow list: if userCan('list');\n      allow create: if userCan('create');\n      allow update: if userCan('update');\n      allow delete: if userCan('delete');\n    }\n  }\n}\n\n```\n\nIn summary, each user has full access to their own \"user scope\" (`/user/\u003cuser-uid\u003e/**`) by default. For any document that is not in the default \"user scope\", a you must have explicit permission to either `get`, `list`, `create`, `update` or `delete` a document in it's `permissions` map/field. The permissions map is of the following shape:\n\n```json\n\"permissions\": {\n    [uid]: {\n        \"get\": true | false,\n        \"list\": true | false,\n        \"create\": true | false,\n        \"update\": true | false,\n        \"delete\": true | false,\n    }, \n    ...\n}\n```\n\nCalling `setDocPerm(uid: string, perm: PermissionMap)` on a document will set the permissions for a given user by modifying the document's permission field accordingly. \n\n\n# Examples\n\n```js\n// examples/components/UserAuth.jsx\n\nimport { useFireauth } from '../firebase/hooks';\n\nexport function UserAuth() {\n    const { user, isLoading, login, logout } = useFireauth();\n\n    return (\n        \u003c\u003e\n            \u003ch1\u003eUser Authentication Example\u003c/h1\u003e\n            \u003cstrong\u003eLogin, logout and manage your authentication status\u003c/strong\u003e\n            {(isLoading \u0026\u0026 \u003cp\u003eLoading...\u003c/p\u003e) || (\n                \u003c\u003e\n                    \u003cp\u003e{(user \u0026\u0026 `Hello, ${user.displayName}`) || 'You are logged out'}\u003c/p\u003e\n                    \u003cbutton disabled={user} onClick={login.withGoogle}\u003e\n                        Login with Google\n                    \u003c/button\u003e\n                    \u003cbutton disabled={!user} onClick={logout}\u003e\n                        Logout\n                    \u003c/button\u003e\n                \u003c/\u003e\n            )}\n            \u003chr /\u003e\n        \u003c/\u003e\n    );\n}\n\n```\n\n```js\n// examples/components/Counter.jsx\n\nimport { useFirestore, useFireauth } from '../firebase/hooks';\n\nexport function CounterExample() {\n    const { user, isLoading } = useFireauth();\n\n    const path = '$.count'; // Same as `/users/${user.uid}.count`\n    const defaultCount = 0; // Used to initialize remote data if it does not exist in Firestore\n    const fallbackCount = -999; // Used when access to resource is denied.\n    const [count, setCount] = useFirestore(path, defaultCount, fallbackCount);\n\n    return (\n        \u003c\u003e\n            \u003ch1\u003eCounter Example\u003c/h1\u003e\n            \u003cstrong\u003e\n                This count is stored in Firestore, so it will be persisted across devices, sessions and\n                reloads.\n            \u003c/strong\u003e\n            {(isLoading \u0026\u0026 \u003cp\u003eLoading...\u003c/p\u003e) || (\n                \u003c\u003e\n                    \u003cp\u003e{getCountInformation(isLoading, user, path)}\u003c/p\u003e\n                    \u003cp\u003eThe current count is: {count}\u003c/p\u003e\n                    \u003cbutton disabled={!user} onClick={() =\u003e setCount(count + 1)}\u003e\n                        {(user \u0026\u0026 'Increase the count!') || 'Login to increase the count'}\n                    \u003c/button\u003e\n                \u003c/\u003e\n            )}\n            \u003chr /\u003e\n        \u003c/\u003e\n    );\n}\n\nfunction getCountInformation(isLoading, user, path) {\n    // Format the path nicely for display on the site...\n    const fullPath = 'firestore:/' + path.replace('$', `/users/${user \u0026\u0026 user.uid}`);\n    // Display information according to loading and user status\n    if (isLoading) {\n        return 'Loading...';\n    } else if (!user) {\n        return `User is logged out and denied access to ${fullPath}, so fallback count is being used`;\n    } else {\n        return `Count is being accessed from user's local data here: ${fullPath}`;\n    }\n}\n\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frioam2%2Fusefire","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frioam2%2Fusefire","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frioam2%2Fusefire/lists"}