react-firebase-hoc

0.2.0 • Public • Published

react-firebase-hoc

React Higher Order Components for Firebase. Compatible with React and React Native.

npm version

Requirements

  • Bundler that supports ES7 Async/await (Both CRA and CRNA supported it)

How to use

  1. Install the package

    npm install react-firebase-hoc
  2. Use them on your component

    import * as firebase from 'firebase';
    import { FetchOnce } from 'react-firebase-hoc';
     
    const firebaseConfig = {...};
    const firebaseApp = firebase.initializeApp(firebaseConfig);
     
    /**
     * later after component declaration...
     * 1st param is the firebaseApp instance
     * 2nd param is the namespace for the fetched data
     * 3rd param is the callback, (db, props, state)
     */
    const MyComponentWithData = FetchOnce(firebaseApp, 'users',
     (db) => db.ref('users'))(MyComponent)
     
    // or you can use it as decorator too
    @FetchOnce(firebaseApp, 'users', (db) => db.ref('users'))
    class MyComponent extends React.Component {...}
  3. You'll get the injected props on your component

    // users is the namespace specified on the first param of HOC
    console.log(this.props.users.loading) // true/false
    console.log(this.props.users.error) // null/object
    console.log(this.props.users.data) // null/object

Callback parameters

You also have access to the props and state on the callback HOC

@FetchOnce(firebaseApp, 'users', (db, props, state) => db.ref(`users/${props.userId}`))

Tips

You can re-wrap the HOC if you always use one firebaseApp instance, for example:

import * as firebase from 'firebase';
import { FetchOnce as FetchOnceOrig } from 'react-firebase-hoc';
 
const firebaseConfig = {...};
const firebaseApp = firebase.initializeApp(firebaseConfig);
 
function FetchOnce(propName, callback) {
  return FetchOnceOrig(firebaseApp, propName, callback);
}

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i react-firebase-hoc

Weekly Downloads

1

Version

0.2.0

License

MIT

Last publish

Collaborators

  • antonybudianto