GithubHelp home page GithubHelp logo

hhy5277 / reactfire Goto Github PK

View Code? Open in Web Editor NEW

This project forked from firebaseextended/reactfire

0.0 1.0 0.0 1.63 MB

ReactJS mixin for easy Firebase integration - DEPRECATED

License: MIT License

JavaScript 100.00%

reactfire's Introduction

ReactFire is deprecated

status: inactive

ReactFire is deprecated. To use Firebase on React application you can use either:

To access the former README you can check out the v1.0.0 tag

Using the Firebase JS SDK in React

To use the Firebase JS SDK in React, you can follow these guidelines:

  • Initialize Firebase in your app once, for instance outside the React components or in a separate module and export the firebase App.
  • Create your Firebase data observers in componentDidMount lifecycle methods.
  • Map your Firebase data to the local state in the data observers.
  • Un-subscribe your Firebase data observers in componentWillUnmount lifecycle methods to avoid memory leaks and unintended behaviors.
  • When updating data: update the data on Firebase directly. Do not update the local state because it won't update the data on Firebase but updating Firebase will trigger your local observers instantly.

Initialize Firebase

Initialize Firebase once, for example in a separate module (e.g. firebase.js) and export the Firebase app. You can find more details on the web setup guides and especially where to find your project's configuration.

Here is an example of a firebase.js module that initializes Firebase:

firebase.js

// Import the Firebase modules that you need in your app.
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/datastore';

// Initalize and export Firebase.
const config = {
  apiKey: '<YOUR-API-KEY>',
  authDomain: '<YOUR-AUTH-DOMAIN>',
  databaseURL: 'https://<YOUR-DATABASE-NAME>.firebaseio.com',
  projectId: '<YOUR-PROJECT-ID>',
  storageBucket: '<YOUR-STORAGE-BUCKET>.appspot.com',
  messagingSenderId: '<YOUR-MESSAGING-SENDER-ID>'
};
export default firebase.initializeApp(config);

Firebase Auth

Here is an example of how you can map the Firebase authentication state to your React component's local state:

import firebase from './firebase.js';

class MyComponent extends React.Component {
  state = {
    isSignedIn: false,
    userProfile: null
  };
  
  componentDidMount() {
    // Updating the `isSignedIn` and `userProfile` local state attributes when the Firebase Auth
    // state changes.
    this.unregisterAuthObserver = firebase.auth().onAuthStateChanged((user) => {
      this.setState({ isSignedIn: !!user, userProfile: user });
    });
  }
  
  componentWillUnmount() {
    // Un-registers the auth state observer.
    this.unregisterAuthObserver();
  }
  
  // ...
}

Firebase Realtime Database

Here is an example of how you can map data from the Realtime Database to your React component's local state:

import firebase from './firebase.js';

class MyComponent extends React.Component {
  state = {
    someData: {}
  };
  
  componentDidMount() {
    // Updating the `someData` local state attribute when the Firebase Realtime Database data
    // under the '/someData' path changes.
    this.firebaseRef = firebase.database().ref('/someData');
    this.firebaseCallback = this.firebaseRef.on('value', (snap) => {      
      this.setState({ someData: snap.val() });
    });
  }
  
  componentWillUnmount() {
    // Un-register the listener on '/someData'.
    this.firebaseRef.off('value', this.firebaseCallback);
  }
  
  // ...
}

Firebase Cloud Datastore

Here is an example of how you can map data from the Cloud Datastore in a React component:

import firebase from './firebase.js';

class MyComponent extends React.Component {
  state = {
    someCollection: {},
    someDocument: null
  };
  
  componentDidMount() {
    // Updating the `someCollection` local state attribute when the Cloud Firestore 'someCollection' collection changes.
    this.unregisterCollectionObserver = firebase.firestore().collection('someCollection').onSnapshot((snap) => {
      const someCollection = {};
      snap.forEach((docSnapshot) => {
        someCollection[docSnapshot.id] = docSnapshot.data();
      });
      this.setState({ someCollection: someCollection });
    });
    
    // Updating the `someDocument` local state attribute when the Cloud Firestore 'someDocument' document changes.
    this.unregisterDocumentObserver = firebase.firestore().doc('/collection/someDocument').onSnapshot((snap) => {
      this.setState({ someDocument: snap.data() });
    });
  }
  
  componentWillUnmount() {
    // Un-register the listeners.
    this.unregisterCollectionObserver();
    this.unregisterDocumentObserver();
  }
  
  // ...
}

Updating data

When updating data, do not modify the local state directly. Modifying the local state will not update the data on Firebase. Instead you should only update your data on Firebase, this will trigger any observers that you have setup locally instantly from cache.

For instance, let's take an app that has a list of todo items stored on Firebase. It also has a text field and a button to add new todos:

import firebase from './firebase.js';

class MyComponent extends React.Component {
  state = {
    todoList: {}, // Mirrors the Todo lsit in Firebase.
    newTodoText: '', // Mirrors the new Todo Text field in the UI.
  };
  
  componentDidMount() {
    // Updating the `todoList` local state attribute when the Firebase Realtime Database data
    // under the '/todoList' path changes.
    this.firebaseRef = firebase.database().ref('/todoList');
    this.firebaseCallback = this.firebaseRef.on('value', (snap) => {      
      this.setState({ todoList: snap.val() });
    });
  }
  
  componentWillUnmount() {
    // Un-register the listener on '/todoList'.
    this.firebaseRef.off('value', this.firebaseCallback);
  }
  
  // This is triggered when the "Add New Todo" button is clicked.
  onSubmit(e) {
    e.preventDefault();
    // Add the new todo to Firebase.
    this.firebaseRef.push({
      text: this.state.newTodoText
    });
    // Clearing the text field.
    this.setState({text: ''});
  }
  
  // ...
}

Note how we are not updating the todoList in the local state. You only need to update Firebase and the Firebase observer that was set up will take care of propagating the changes and updating the local state.

Migrating from ReactFire

To migrate from ReactFire to using the Firebase JS SDK first remove the ReactFireMixin that was applied to any of your React components.

Migrate bindAsObject calls

In all component that are using bindAsObject(firebaseRef, bindVar, cancelCallback) change from:

componentWillMount: function() {
  var ref = firebase.database().ref().child("users/fred");
  this.bindAsObject(ref, "user");
}

componentWillUnmount: function() {
  this.unbind("user");
}

to:

componentDidMount: function() {
  this.firebaseCallback = firebase.database().ref('/users/fred').on('value', function(snap) {      
    this.setState({ user: snap.val() });
  });
}
  
componentWillUnmount: function() {
  firebase.database().ref('/users/fred').off('value', this.firebaseCallback);
}

Migrate bindAsObject calls

In all component that are using bindAsArray(firebaseRef, bindVar, cancelCallback) change from:

componentWillMount: function() {
  var ref = firebase.database().ref("items");
  this.bindAsArray(ref, "items");
}

componentWillUnmount: function() {
  this.unbind("items");
}

to:

componentDidMount: function() {
  this.firebaseCallback = firebase.database().ref('/items').on('value', function(snap) {    
    var items = [];
    snap.forEach(function(itemSnap) {
      items.push(itemSnap.val());
    });
    this.setState({ items: items });
  });
}
  
componentWillUnmount: function() {
  firebase.database().ref('/items').off('value', this.firebaseCallback);
}

reactfire's People

Contributors

abeisgoat avatar adrw avatar cskiwi avatar danielmahal avatar edi avatar firebase-ops avatar haroenv avatar insin avatar jaylandro avatar joeyyang avatar llad avatar martellaj avatar mimming avatar mjackson avatar nicolasgarnier avatar npmcdn-to-unpkg-bot avatar puf avatar ramyathulasingam avatar samtstern avatar shashankanataraj avatar startupandrew avatar timotius02 avatar tstirrat avatar

Watchers

 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.