2.0.0-canary.d5a1543 • Published 7 years ago

reactfire v2.0.0-canary.d5a1543

Weekly downloads
3,377
License
MIT
Repository
github
Last release
7 years ago

Reactfire

npm install reactfire
# or
yarn add reactfire

Hooks, Context Providers, and Components that make it easy to interact with Firebase.

By default, every reactfire hook throws a Promise until it has connected to Firebase, allowing you to use Suspense to render a fallback component. If you don't want reactfire to throw a promise, pass an initial value to a reactfire hook. It will emit the initial value right away instead of throwing a promise.

Quickstart

āš› + šŸ”„ = 🌯

We'll build a web app that displays, in real time, the tastiness of a burrito. It will listen to Cloud Firestore for its data, and we'll configure Firebase Performance Monitoring so we can get some perf stats.

Prerequisite: make sure you have Node.js installed.

  1. In a terminal, create a fresh React app and cd into its directory.

    npx create-react-app myapp
    cd myapp
  2. Install reactfire and the Firebase SDK

    yarn add firebase reactfire@canary
    # or
    npm install firebase reactfire@canary
  3. Create a document in Cloud Firestore.

    1. Go to the Database tab in the Firebase console. If your project doesn't have a Cloud Firestore instance yet, initialize it in locked mode
    2. Add a document

      1. In the Data tab of the console, click Add Collection

      2. Name the collection tryreactfire

      3. Add a document with ID burrito and boolean field yummy: true

      new document screenshot

    3. Add the following to your security rules and click Publish

      match /tryreactfire/burrito {
        allow read: if true;
        allow write: if request.auth.uid != null;
      }
  4. Modify src/index.js

    1. Import firebase and reactfire

      //...
      import { FirebaseAppProvider } from 'reactfire';
      import 'firebase/performance';
      //...
    2. Wrap your app in a FirebaseAppProvider and provide the config object from the Firebase console

      //...
      const firebaseConfig = {
        /* add your config object from Firebase console */
      };
      ReactDOM.render(
        <FirebaseAppProvider firebaseConfig={firebaseConfig} initPerformance>
          <App />
        </FirebaseAppProvider>,
        document.getElementById('root')
      );
      //...
  5. Modify src/App.js

    1. Import firebase/firestore as well as the useFirestoreDoc and useFirebaseApp hooks

      //...
      import 'firebase/firestore';
      import {
        useFirestoreDoc,
        useFirebaseApp,
        SuspenseWithPerf
      } from 'reactfire';
      //...
    2. Add a function component

      //...
      function Burrito() {
        // create a ref
        const firebaseApp = useFirebaseApp();
        const burritoRef = firebaseApp
          .firestore()
          .collection('tryreactfire')
          .doc('burrito');
      
        // get the doc. just one line!
        const burritoDoc = useFirestoreDoc(burritoRef);
      
        // get the value from the doc
        const isYummy = burritoDoc.data().yummy;
      
        return <p>The burrito is {isYummy ? 'good' : 'bad'}</p>;
      }
      //...
    3. Render your component inside of a Suspense tag

    We need to do this because useFirestoreDoc throws a Promise while it is waiting for a response from Firestore. Suspense will catch the Promise and render fallback until the Promise is resolved.

    Replace the App function with the following:

    //...
    function App() {
      return (
        <div className="App">
          <SuspenseWithPerf
            fallback={'loading burrito status...'}
            traceId={'load-burrito-status'}
          >
            <Burrito />
          </SuspenseWithPerf>
        </div>
      );
    }
    //...
  6. Run your app!

    yarn start
    # or
    npm run start
  7. Edit the value of yummy in the Firebase console, and watch it update in real time in your app! šŸ”„šŸ”„šŸ”„

  8. But what about Firebase Performance Monitoring?

    By passing the initPerformance prop to FirebaseAppProvider, our app will automatically measure common performance stats, as well as report on our custom trace, load-burrito-status, that we set in the traceId prop of SuspenseWithPerf.

    However, Firebase Performance Monitoring can take about 12 hours to crunch your data and show it in the Performance tab of the Firebase console.

    This is an example of some of the stats in the Firebase Performance Monitoring console after 12 hours:

    Performance screenshot

Docs

ToC

Providers

FirebaseAppProvider

A React Context Provider that allows the useFirebaseApp hook to pick up the firebase object.

Sample usage
const firebaseConfig = {
  /* web app config from Firebase console */
};

<FirebaseAppProvider firebaseConfig={firebaseConfig} initPerformance>
  <App />
</FirebaseAppProvider>;
Props
PropTypeDescription
configObjectthe web app config object usually passed to initializeApp
initPerformanceboolWhether or not to initialize Firebase Performance Monitoring

Hooks

useFirebaseApp

When called from a component nested inside a FirebaseAppProvider, useFirebaseApp returns the root Firebase object.

IMPORTANT: By default, useFirebaseApp returns a firebase object without any products attached to it (e.g. you can't call firebase.firestore(). To do that, you need to import 'firebase/firestore' or any other Firebase feature as needed)

Returns

firebase

useUser

Get the user that is currently signed in.

Throws a Promise by default

Parameters
ParameterTypeDescription
auth ?Authoptional auth object. If not provided, useUser will use useFirebaseApp to find the Auth object.
options ?ReactFireOptionsOptions. This hook will not throw a Promise if you provide startWithValue.
Returns

User

useFirestoreDoc

Listen to a Firestore Document.

Throws a Promise by default

Parameters
ParameterTypeDescription
refDocumentReferenceA reference to the document you want to listen to
options ?ReactFireOptionsOptions. This hook will not throw a Promise if you provide startWithValue.
Returns

DocumentSnapshot

useFirestoreCollection

Listen to a Firestore Collection.

Throws a Promise by default

Parameters
ParameterTypeDescription
refCollectionReferenceA reference to the collection you want to listen to
options ?ReactFireOptionsOptions. This hook will not throw a Promise if you provide startWithValue.
Returns

QuerySnapshot

useDatabaseObject

Listen to a Realtime Database Object.

Throws a Promise by default

Parameters
ParameterTypeDescription
refReferenceA reference to the object you want to listen to
options ?ReactFireOptionsOptions. This hook will not throw a Promise if you provide startWithValue.
Returns

QueryChange

useDatabaseList

Listen to a Realtime Database list.

Throws a Promise by default

Parameters
ParameterTypeDescription
refReferenceA reference to the list you want to listen to
options ?ReactFireOptionsOptions. This hook will not throw a Promise if you provide startWithValue.
Returns

QueryChange[]

useStorageTask

Listen to a Storage UploadTask

Throws a Promise by default

Parameters
ParameterTypeDescription
taskUploadTask
refReference
options ?ReactFireOptions
Returns

UploadTaskSnapshot

useStorageDownloadURL

Subscribe to a storage blob's download URL

Throws a Promise by default

Parameters

ParameterTypeDescription
refReference
options ?ReactFireOptions
Returns

string

Components

AuthCheck

Renders children if a user is signed in and meets the required claims. Renders fallback otherwise.

Props
PropertyType
authAuth
childrenReact.Component
fallbackReact.Component
requiredClaimsObject

SuspenseWithPerf

Starts a Firebase Performance Monitoring trace and ends it when suspense stops suspending.

Props
PropertyType
childrenReact.Component
fallbackReact.Component
firePerf ?any
traceIdstring

ReactFireOptions

PropertyType
startWithValueany

Contributing

For development

  1. yarn install
  2. cd into the reactfire/reactfire directory. run yarn run watch.
  3. In a new terminal, cd into the reactfire/sample-simple directory. run yarn start.
  4. Head over to https://localhost:3000 to see the running sample

Testing

  1. cd into the reactfire/reactfire directory
  2. run yarn test
4.2.3

3 years ago

4.2.2

4 years ago

4.2.1

5 years ago

4.2.0

5 years ago

4.1.1

5 years ago

4.0.1

5 years ago

4.1.0

5 years ago

4.0.0

5 years ago

3.0.0

5 years ago

4.0.0-rc.1

5 years ago

4.0.0-rc.2

5 years ago

3.0.0-rc.3

5 years ago

3.0.0-rc.2

5 years ago

3.0.0-rc.1

5 years ago

3.0.0-rc.0

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0-rc.3

6 years ago

2.0.0-rc.2

6 years ago

2.0.0-rc.1

6 years ago

2.0.0-rc.0

6 years ago

2.0.0-alpha.3

6 years ago

2.0.0

7 years ago

2.0.0-alpha.2

7 years ago

2.0.0-alpha.1

7 years ago

1.0.0

10 years ago

0.7.0

10 years ago

0.6.0

10 years ago

0.5.1

11 years ago

0.5.0

11 years ago

0.4.0

12 years ago

0.3.0

12 years ago

0.2.0

12 years ago

0.1.6

12 years ago

0.1.5

12 years ago

0.1.4

12 years ago