EzDev.org

reactfire

reactfire - ReactJS mixin for easy Firebase integration


Firebase hosting + React with webpack

Is there a way to add Firebase hosting to React project that utilizes webpack? Specifically, I am trying to add it to https://github.com/mxstbr/react-boilerplate

This is my firebase.json file

{
  "hosting": {
    "firebase": "name",
    "public": "app",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

When I call firebase serve the page is empty. However, if I do npm start the app works correctly. So, the JS/React code is not being injected into the index.html, which is

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Welcome to Firebase Hosting</title>
  </head>
  <head>
    <!-- The first thing in any HTML file should be the charset -->
    <meta charset="utf-8">
    <!-- Make the page mobile compatible -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Allow installing the app to the homescreen -->
    <link rel="manifest" rel='nofollow' href="manifest.json">
    <meta name="mobile-web-app-capable" content="yes">
    <title>React.js Boilerplate</title>
  </head>
  <!-- The app hooks into this div -->
  <!-- A lot of magic happens in this file. HtmlWebpackPlugin automatically includes all assets (e.g. bundle.js, main.css) with the correct HTML tags, which is why they are missing in this HTML file. Don't add any assets here! (Check out webpackconfig.js if you want to know more) -->
  <body>
  <div id="app"></div>
  <div id="message">
      <h1>Welcome to Firebase Hosting</h1>
    </div>
  </body>
</html>

Source: (StackOverflow)

EPERM error installing ReactFire in jspm

I'm trying to install ReactFire with jspm. The command I use is:

jspm install npm:reactfire

It installs a bunch of dependencies, then gives this error:

warn Error on build
     Error: EPERM: operation not permitted, open 'C:\Users\aldel\AppData\Local\.jspm\packages\npm\firebase@3.1.0\app.js'
         at Error (native)

err  Error building package npm:firebase.

warn Installation changes not saved.

Sometimes it gives the error on auth.js instead of app.js (same directory). It seems like the whole directory (firebase@3.1.0, that is) is created by jspm when running the above command, so it seems like it gets created, and then is immediately inaccessible by its creator.

I've tried:

  • adding -f to the jspm command line
  • installing before or after Firebase, React, and React-Dom
  • running with administrator privileges
  • clearing caches in both npm and jspm
  • messing with file and directory permissions
  • (edit) adding various -o options to try to prevent the Firebase dependency from installing from npm

I also just noticed that the same error happens if I do jspm install npm:firebase. I think the problem above happens when Firebase is installed as a dependency of ReactFire. Just doing jspm install firebase installs it from github:firebase/firebase-bower, not from npm:firebase (maybe because npm:firebase doesn't work??).

So I think it's a problem with how npm:firebase gets downloaded and installed, and/or with how npm:reactfire depends on npm:firebase. But I'm not sure how to fix or work around it. I'm pretty new to npm and jspm.

And I'm on Windows. Sorry.

Any ideas?


Source: (StackOverflow)

Retrieve Data from a Many-to-Many Structure Similar to Prase query.include

We are migrating an app from Parse to Firebase and I'd like to build a UI where I can show the student name along with the classroom that s/he belongs to from the following Firebase data structure. For example, the class room name for aluck is 10th Grade.

{
    "students": {
        "aluck": {
            "firstName": "Andrew",
            "lastName": "Luck",
            "classroom": "-KJlJhyNH6ImKke-qAd-"
        },
        "bmorino": {
            "firstName": "Beth",
            "lastName": "Morino",
            "classroom": "-KJlJhyNH6ImKke-qAd-"
        }
    },
    "classRooms": {
        "-KJlJhyNH6ImKke-qAd-": {
            "location": "Down stairs",
            "name": "10th Grade",
            "students": {
                "aluck": true,
                "bmorino": true,
            }
        }
    }
}

My assumption was when I do something like this using the Firebase JavaScript SDK,

var db = firebase.database(); 
db.ref("students/aluck").on("value", function(snap) { 
    // success method will expose the classroom object with it 
}); 

it will expose the classRooms object, but it does not.

In Parse, I was able to do

var query = new Parse.Query(Student);
query.include("ClassRoom");

and it'll expose both the Student and ClassRoom objects.

Any help is appreciated.


Source: (StackOverflow)

Save edited data to firebase using reactjs

I am creating an app where the user data are registered using reactjs in frontend and firebase as a backend. I could save data to firebase. I could edit and delete the data but could not saved edited data to firebase. What should I do to edit data? I used child_changed but still did not work.

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
        userInfo:userInfo
      }
    this.userRef = new Firebase('https://***.firebaseio.com/users/');
    this.createUser = this.createUser.bind(this);
    this.saveUser = this.saveUser.bind(this);
    this.deleteUser = this.deleteUser.bind(this);

  }

  loadData(){
    this.userRef.on('value', snap => {
      let userInfo = [];
      snap.forEach( data => {
        let userData = data.val();
        userData.id = data.name();
        userInfo.push(userData);
      });
      this.setState({ userInfo });
    });

    this.userRef.on('child_removed', (dataSnapshot) =>{
        delete this.state.userInfo[dataSnapshot.key()];
        this.setState({ userInfo: this.state.userInfo });
    });

  }

  componentDidMount(){
    this.loadData();
  }

  createUser(user){
    this.userRef.push(user);
  }

  saveUser(oldUser, newUser){
    console.log('olduser',oldUser);
    console.log('newuser', newUser);
    // TODO - optimize this code
    const foundUser = _.find( this.state.userInfo, user =>
        user.name === oldUser.name
    );
    const foundContact = _.find( this.state.userInfo, user =>
        user.contact === oldUser.contact
    );
    const foundAddress = _.find( this.state.userInfo, user =>
        user.address === oldUser.address
    );
    const foundEmail = _.find( this.state.userInfo, user =>
        user.email === oldUser.email
    );
    const foundUsername = _.find( this.state.userInfo, user =>
        user.username === oldUser.username
    );
    const foundPassword = _.find( this.state.userInfo, user =>
        user.password === oldUser.password
    );
    console.log('foundUser', foundUser);
    console.log('foundUser.name',foundUser.name);
    foundUser.name = newUser.name;
    foundContact.contact = newUser.contact;
    foundAddress.address = newUser.address;
    foundEmail.email = newUser.email;
    foundUsername.username = newUser.username;
    foundPassword.password = newUser.password;
  }

Source: (StackOverflow)

Call function when data is set in state with reactfire

I'm using reactfire to get some data from my firebase database.

  componentWillMount() {
    const ref = Database.ref(`products`);
    this.bindAsArray(ref, `products`);
  }

The bindAsArray function automatically injects the products in my state. How can I call a function when the products are set in the state?


Source: (StackOverflow)

What is the correct way to use `Mixin` in `React` ES6

In ES5:

var TodoApp = React.createClass({
  mixins: [ReactFireMixin], //working fine
  ...
});

In ES6: (created using react cli )

class TodoApp extends Component {
    constructor(props) {
        super(props)
    }
    mixins= [ReactFireMixin] //not working
    ...
}

what is the correct way of doing this?


Source: (StackOverflow)

ReactFire isn't loading data from Realtime Database

I have a Firebase project with a realtime database which contains a few test items, in this structure:

project-21093
|_items
  |_item1
    |_name: "Name"
    |_category: "Category"
  |_item2
    |_name: "Name2"
    |_category: "Category:

My index.html file includes the <script src="https://www.gstatic.com/firebasejs/3.3.0/firebase.js"></script> tag, and this is my index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import firebase from 'firebase/app';
require("firebase/auth");
require("firebase/database");
import ReactFireMixin from 'reactfire';
require("./styles/customisations.scss");

// Initialize Firebase
var config = {
  apiKey: "key",
  authDomain: "auth",
  databaseURL: "url",
  storageBucket: "storage",
};
firebase.initializeApp(config);

var App = React.createClass({
  mixins: [ReactFireMixin],

  getInitialState: function() {
    return {
      items: []
    };
  },

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

  render: function() {}
})

The whole config section was taken directly from what the project page gave me. It didn't work in index.html as was instructed, so I loaded it here. I'm not sure which requirements exactly were needed so I loaded a bunch.

My problem is that this.state.items is always empty, despite having items in my realtime database, which I assume are meant to be bound to the this.state.items array in componentWillMount. Since the docs never specify what parameter needs to be passed in to the firebase.database().ref() call, I've tried everything from project/items, project-21093/items and variations to database/data/items with no success. The React plugin of Chrome dev tools clearly shows me the empty array. What am I missing to load this data successfully?


Source: (StackOverflow)

reactfire React+firebase "contains an invalid key (.key) in property"

I get an error when trying to use update() or set()

My relevant code:

const ref = new Firebase('https://whatever.firebase.org/employees');
export default class EmployeeNew extends React.Component {
...
  this.update = () => {
    console.log(this.state, this.props.employee['.key']);
    ref.child(this.props.employee['.key']).set(this.state); // <-- no-dice
    // ref.update(this.state); <-- also fails.
  }
...
}

Output of console logs, when update is invoked as written above:

Object {avatar: "https://somevalue.png", name: "Bananaman", .key: "-KDObp8r82Ornrrmfbk5"}
Object "-KDObp8r82Ornrrmfbk5"

Error in browser console:

app.js:28366 Uncaught Error: Firebase.set failed: First argument  contains an invalid key (.key) in property 'employees.-KDObp8r82Ornrrmfbk5'.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

Things i have tried:

  ref.update(this.state); // same error
  ref.update({this.props.employee['.key']: this.state}); // same error

Source: (StackOverflow)

React + Firebase Empty Array

I'm trying to render my items in my Firebase database (of which I have 3) to my React component's page and am having a little difficulty.

var config = {
  // ...
};

firebase.initializeApp(config);

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    }
  }

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

  render() {
    return (
      <div>
        { this.state.items.map(function (item, i) {
          return (
            <h1 className="white">Item</h1>
          )
        }) }
      </div>
    );
  }
}

reactMixin(App.prototype, ReactFireMixin);

export default App;

Am I doing this correctly, shouldn't I be seeing three repeated <h1> elements?

Any help is appreciated. Thanks in advance!

UPDATE:

JSbin example: http://jsbin.com/xodobohexi/edit?html,js,console,output


Source: (StackOverflow)

How to sync data from Firebase to React using ES6?

I am following tutorial from Tyler McGinnis on using firebase on react, but I cannot get my app to sync to my firebase. The tutorial was originally done not on ES6. This is the meat of the code:

var Profile = React.createClass({
  mixins: [ReactFireMixin],
  getInitialState: function(){notes: ['some','notes']},

  componentDidMount: function(){
    this.ref = new Firebase('https://github-note-taker.firebaseio.com/');
    var childRef = this.ref.child(this.props.params.username);
    this.bindAsArray(childRef, 'notes');
  }
  ...
  //render
  <Notes username={this.props.params.username} notes={this.state.notes} />

This will sync notes to FB database and renders note array

I have a firebase database populated with some amount of data. When I access the page, my Note component is only displaying the initial state, not the firebase data. I am new at Firebase. After researching, I came up with ES6 version of it:

var base = Rebase.createClass({
  apiKey: ...,
  authDomain: ...,
  databaseURL: ...,
  storageBucket: ...,
  messagingSenderId: ...
});

class Profile extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      notes: [1,2,3],
     }
  }
  init(){
    this.ref = base.syncState(`/profile/${this.props.routeParams.username}`, {
      context: this,
      asArray: true,
      state: 'notes'
    });

    helpers.getGithubInfo(this.props.routeParams.username)
      .then((dataObj) => {
        this.setState({
          bio: dataObj.bio,
          repos: dataObj.repos
        });
      });

  }
  componentDidMount(){
    this.init();
  }
  componentWillUnmount(){
    base.removeBinding(this.ref);
  }
  componentWillReceiveProps(){
    base.removeBinding(this.ref);
    this.init();
  }
  //render
  <Notes notes={this.state.notes} />

I am sure I miss something, but I am not sure what it is. How can I use ES6 to sync Firebase to my React App?


Source: (StackOverflow)

Why is my state getting mapped one too many times in ReactJS?

Hello i'm trying to map my data, which i feched from my Firebase, into a Row of Cards. But since i have the state defined in my constructor, one card gets returned with no values at the start. what can i do to avoid the returning of this first empty Card Component ? Thanks in advance.
(the Card Component is a Component with a Thumbnail which i imported)

class  List extends Component {
      constructor(props){
        super(props)

        this.db = firebase.database().ref().child('app').child('cards');

        this.state = {
            cards: [
              {
                id: "",
                cardDesc: "",
                cardPrice: "",
                cardHeading: "",
              }
            ]
          }
        }

      componentWillMount (){
        const previousCards = this.state.cards

        this.db.on('child_added', snap => {
          previousCards.push ({
            id: snap.key,
            cardDesc: snap.val().cardDesc,
            cardPrice: snap.val().cardPrice,
            cardHeading: snap.val().cardHeading,
          })
          this.setState ({
            cards: previousCards
          })
        })
      }

      render(){
        return(
          <div className='list'>
          <Row>
          { this.state.cards.map((card) => {
            return(<Card cardHeading={card.cardHeading} cardDesc={card.cardDesc}
               cardPrice={card.cardPrice} key={card.id} />)
                })
          }
          </Row>
          </div>
        )
      }
    }

    export default List

Source: (StackOverflow)

Cannot retrieve firebase json from database using reactFire

I am tring to connect to my firebase using reactFire

This is my root of json "glossary"

var firebaseRef = firebase.database().ref('/glossary');
console.log(firebaseRef)

But when in console if get the following

U {k: Bh, path: K, n: ce, bc: false}
bc
:
false
k
:
Bh
n
:
ce
path
:
K
__proto__
:
Y

Source: (StackOverflow)

Delete is not working in react and firebase

I have created an app where the user data are registered using reactjs in frontend and firebase as a backend. I could save data to firebase. I could edit and delete the data but could not saved edited data to firebase and also my deleteUser event wont remove the deleted node. What might be the reason ?

Here is my code

const userInfo = [
      { id:1, name:'',contact:'',address:'',email:'',username:'',password:'' }
    ];

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
        userInfo:userInfo
      }
    this.userRef = new Firebase('https://***.firebaseio.com/users/');
    this.createUser = this.createUser.bind(this);
    this.saveUser = this.saveUser.bind(this);
    this.deleteUser = this.deleteUser.bind(this);

  }

  loadData(){
    this.userRef.on('value', snap => {
      let userInfo = [];
      snap.forEach( data => {
        let userData = data.val();
        userData.id = data.name();
        userInfo.push(userData);
      });
      this.setState({ userInfo });
    });

    this.userRef.on('child_removed', (dataSnapshot) =>{
        delete this.state.userInfo[dataSnapshot.key()];
        this.setState({ userInfo: this.state.userInfo });
    });

  }

  componentDidMount(){
    this.loadData();
  }

  createUser(user){
    this.userRef.push(user);
  }

  saveUser(oldUser, newUser){
    console.log('olduser',oldUser);
    console.log('newuser', newUser);
    // TODO - optimize this code
    const foundUser = _.find( this.state.userInfo, user =>
        user.name === oldUser.name
    );
    const foundContact = _.find( this.state.userInfo, user =>
        user.contact === oldUser.contact
    );
    const foundAddress = _.find( this.state.userInfo, user =>
        user.address === oldUser.address
    );
    foundUser.name = newUser.name;
    foundContact.contact = newUser.contact;
    foundAddress.address = newUser.address;
  }

  deleteUser(id){
    console.log(id);
    const dltUserRef = new Firebase('https://***.firebaseio.com/users').child(id);
    console.log('dlt',dltUserRef);
    dltUserRef.remove();
  }

  render() {
    return (
      <div>
        <FormBox createUser = { this.createUser } />
        <UsersList
            userInfo = { this.state.userInfo }
            saveUser = { this.saveUser }
            deleteUser = { this.deleteUser } />
      </div>
    );
  }
}

user-list-item.js

import React, { Component } from 'react';

export default class UserslistItem extends Component {
    constructor(props){
        super(props);

        this.state = { isEditing: false };

        this.onEditClick = this.onEditClick.bind(this);
        this.onCancelClick = this.onCancelClick.bind(this);
        this.onSaveClick = this.onSaveClick.bind(this);
    }

    onEditClick(){
        this.setState({ isEditing: true });
    }

    onCancelClick(){
        this.setState({ isEditing: false });
    }

    onSaveClick(event){
        event.preventDefault();
        const oldUser = [
            {
                name:this.props.name,
                address:this.props.address,
                contact:this.props.contact
            }
         ];
        const newUser = [
            {
                name: this.refs.editName.value,
                address: this.refs.editAddress.value,
                contact: this.refs.editContact.value
             }
        ];
        // console.log('old user is', oldUser);
        // console.log('new user is', newUser);
        this.props.saveUser( ...oldUser, ...newUser );
        this.setState({ isEditing: false });
    }


        return(
                <div className = "buttons">
                    <button className="btn btn-warning" onClick = { this.onEditClick }>Edit</button>
                    <button className="btn btn-danger" onClick = { this.props.deleteUser.bind(this, this.props.id) }>Delete</button>
                </div>
            );

    }

    render() {
        return (
            <div className = "container" >
                <div className="row">
                    <div className="col-md-4">
                        <div className="card card-block">
                             { this.renderUserSection() }
                            { this.renderActionSection() }
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

Deleting is working now. But how could i save edited data ?


Source: (StackOverflow)

Controlling Page State With re-base or reactfire

currently looking in to making a new web app with Firebase, React and re-base or reactfire. I understand that Flux when used with Firebase does not make complete sense, and they don't work well together. My question is, if I do not use Flux or Redux, but instead just re-base or reactfire how do I control the page's state? For instance, knowing a drop down is active.


Source: (StackOverflow)

How to use a mixin in React v16 ES6/ES7

Based on the documentation for ReactFire, the way to use it is by adding a mixin to the component.

Mixins are not the way to go, HoC or Decorators should be used instead

So I wanted to create a Decorators, although the only way I found to use mixins is through React.creatClass(), which is deprecated and not even available in the latest React version.

How can I use a mixin with the latest version (v16.0)?

Or is there another way to use the library?


Source: (StackOverflow)