Code Monkey home page Code Monkey logo

reactfire's Introduction

ReactFire

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

What is ReactFire?

  • Easy realtime updates for your function components - Hooks like useUserand useFirestoreCollection let you easily subscribe to auth state, realtime data, and all other Firebase SDK events. Plus, they automatically unsubscribe when your component unmounts.
  • Access Firebase libraries from any component - Need the Firestore SDK? useFirestore. Remote Config? useRemoteConfig.
  • Safely configure Firebase libraries - Libraries like Firestore and Remote Config require settings like enablePersistence to be set before any data fetches are made. This can be tough to support in React's world of re-renders. ReactFire gives you useInitFirestore and useInitRemoteConfig hooks that guarantee they're set before anything else.

Install

# npm
npm install --save firebase reactfire

# or

# yarn
yarn add firebase reactfire

Depending on your targeted platforms you may need to install polyfills. The most commonly needed will be globalThis and Proxy.

Docs

Example use

Check out the live version on StackBlitz!

import React from 'react';
import { render } from 'react-dom';

import { doc, getFirestore } from 'firebase/firestore';
import { FirebaseAppProvider, FirestoreProvider, useFirestoreDocData, useFirestore, useFirebaseApp } from 'reactfire';

const firebaseConfig = {
  /* Add in your config object from the Firebase console */
};

function BurritoTaste() {
  // access the Firestore library
  const burritoRef = doc(useFirestore(), 'tryreactfire', 'burrito');

  // subscribe to a document for realtime updates. just one line!
  const { status, data } = useFirestoreDocData(burritoRef);

  // check the loading status
  if (status === 'loading') {
    return <p>Fetching burrito flavor...</p>;
  }

  return <p>The burrito is {data.yummy ? 'good' : 'bad'}!</p>;
}

function App() {
  const firestoreInstance = getFirestore(useFirebaseApp());
  return (
    <FirestoreProvider sdk={firestoreInstance}>
      <h1>๐ŸŒฏ</h1>
      <BurritoTaste />
    </FirestoreProvider>
  );
}

render(
  <FirebaseAppProvider firebaseConfig={firebaseConfig}>
    <App />
  </FirebaseAppProvider>,
  document.getElementById('root')
);

Status

Status: Experimental

This repository is maintained by Googlers but is not a supported Firebase product. Issues here are answered by maintainers and other community members on GitHub on a best-effort basis.

Extra Experimental concurrent mode features

These features are marked as extra experimental because they use experimental React features that will not be stable until sometime after React 18 is released.

  • Loading states handled by <Suspense> - ReactFire's hooks throw promises that Suspense can catch. Let React handle loading states for you.
  • Automatically instrument your Suspense load times - Need to automatically instrument your Suspense load times with RUM? Use <SuspenseWithPerf />.

Enable concurrent mode features by following the concurrent mode setup guide and then setting the suspense prop in FirebaseAppProvider:

<FirebaseAppProvider firebaseConfig={firebaseConfig} suspense={true}>

See concurrent mode code samples in example/withSuspense

reactfire's People

Contributors

allcontributors[bot] avatar banyan avatar catrawalkar avatar codercatdev avatar danielmahal avatar davideast avatar dependabot[bot] avatar firebase-ops avatar insin avatar jamesdaniels avatar jaylandro avatar jhuleatt avatar justjish avatar llad avatar mikeverhees avatar mikkimichaelis avatar mimming avatar mjackson avatar nicolasgarnier avatar prescottprue avatar puf avatar raicuparta avatar ramyathulasingam avatar renaudrohlinger avatar samtstern avatar seanemmer avatar shashankanataraj avatar shelcindra avatar steveasher avatar timotius02 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reactfire's Issues

Upgrade dependency to include React 15.0.0

Change log for React 15.0.0 here.

I'll gladly take a PR from the community on this one if anyone sees this. We need to add 15.x.x here and here as well as upgrade all dev dependencies here to 15.x.x. We also should update the React dependency numbers in the README.md here. If all tests pass and the examples all still work, we should be good to ship it.

this.data not being cleaned up

Hello! ๐Ÿค™

I'm building this messenger-like application, on top of React and Firebase, obviously, and, I've been pulling my hair out for more than 2 hours trying to find out what was causing the weird behavior.

  1. Upon login, I am listening to some rooms ( of users ), then upon room selection I start listening to messages belonging to that room.

  2. The issue arose when a user logs out, and then logs back in from another account for example.
    Upon componentWillUnmount the references get unbinded, so that's all nice and cool.

  3. So, logging back in with another user, even though there is no listener nor reference anymore, I am immediately seeing the "old" messages popping up inside the ConversationView component.

After hours of trying to figure out what is happening.. I finally decided to start looking at what exactly is this mixin doing. Luckily, I quickly realised that we are storing reference data inside this.data but we're not deleting it when the reference gets unbinded.

Therefore, my component's state was automatically being populated with the old reference values from within this.data which were saved when the previous account was logged in.

Note that it doesn't affect components which bind references inside componentWillMount, since those will pull new data anyway. But for the ones which are waiting for data to be binded... the "old" data ( from the previous bind -- previous logged in account ) gets sent towards the component's state once you bind any other reference.

I created a PR with a fix here #121 , which implies cleaning the unbinded variable, as it should.

bindAsPrimitive

When writing complex form components, it's practical to bind strings directly to state, instead of needing to check ".value" each time. Alternatively if there was an option in bindAsObject to always map to ".value".

It makes the workflow more challenging as is, because you can't firebase bind and link state on the same component state key (three-way binding) without writing all the code.

Example featuring auth?

This mixin is great, and the examples are very helpful, but I would love to see an example of how this works with authentication.

Where in the process would we ref.authWithCustomToken() and ref.unauth() ?

Bonus: Are there best practices for auith error handling in a React component using the Reactfire mixin? What if the user is trying to access data to which he doesn't have access rights?

An example capturing this would be awesome. I am happy to contribute, but I am not really sure how this should be done.

Upgrading to 0.5.0 throws: this.state.newsItems is already bound to a Firebase reference

So I'm probably doing something wrong? In 0.4.0 the code below worked fine when filtering a news list by year but now Reactfire is complaining that newsItems is already bound to a Firebase reference.

componentDidMount: function() { // INITIAL LOAD
    this.getNewsList(this.props.query.year);
},

componentWillReceiveProps: function (newProps) { // FILTERING
    this.getNewsList(newProps.query.year);
},

getNewsList: function(filterYear) {
    var newsItemsRef = this.firebaseRefs["newsItems"] || new Firebase("https://XXXXXXXXXX.firebaseio.com/news");

    if(filterYear) {
        this.bindAsObject(newsItemsRef.orderByChild("_year").equalTo(parseInt(filterYear)), "newsItems");   
    }
    else {
        this.bindAsObject(newsItemsRef.orderByPriority(), "newsItems");
    }   
}

The two examples you have (Todo and Comments) never refresh/filter an existing array/object (only updating or deleting from it) so I'm wondering if you can point me in the right direction? Am I supposed to unbind the list before refreshing it? (This will make the list flash to empty before it's filled, something I'd like to avoid)

componentWillReceiveProps: function (newProps) { // FILTERING
    this.unbind("newsItems");
    this.getNewsList(newProps.query.year);
},

Removing records from Firebase not reflecting correctly in app

Let me set the stage for you. Small todo list app. List of todo items are stored in a Firebase database, they have 2 properties (text and done). My todo list app has 2 ways to delete records from the database: delete individual items or delete all that are done.

I'm finding that if I have a list of 3 items, say A, B, and C, and I delete A, the list is rendered incorrectly and instead of being B, C it will be A, B, even though the correct item was deleted in the database and ReactFire returned the correct list of items!

I'm unsure of what to do. You can see the code I'm having trouble with in a branch I set up for you, complete with your own db to play with (already added test items in for you). To run the code, just clone, npm install, and gulp.

Please reach out if I can provide anything else!

Iterating over bindAsArray items for .key

Using .map(), how would I be able to iterate over items to add the .key value within each object in the array, as an ID?

{this.props.state.items.map((item, i) =>
      <li key={i} id={item.key}>{item.text}</li>
}

{item.key} doesn't render anything, it would seem that I'd need {item..key} but of course that throws a syntax error.

screen shot 2016-09-28 at 9 24 58 pm

Any plans to provide a redux adapter?

Hi folks!

Does the team have any plans of providing an adapter that allows firebase to play nicely with redux?

State management in react apps is most popularly driven by redux but I was surprised to find no literature at all on the topic. Atleast it would be beneficial for the community to understand how the core team is thinking about redux-firebase integration?

Add TypeScript / Flow typings

We should provide TypeScript and/or Flow typings for consumers of this repo. Does anyone have any preference for either? TypeScript seems more popular overall and is generally what we use with other Firebase repos, but Flow seems more popular in the React ecosystem due to the Facebook connection. Does anyone know how we can provide both in an easy way?

If using (React + Redux) and firebase as main backend database, how would i host the project?

I want to use firebase as my main backend database storage, i also want to use Redux with React. I am just confused as to how i would host my project. I can't host on firebase i think since this will be a node app. I'm a Node newbie , so pardon me for being ignorant but if i use redux in client side only will npm compile to static js files where i can use firebase hosting?

react 0.13.x dependency causes multiple react versions to be installed

Reactfire has a strict 0.13.x dependency. If you start using 0.14.x there is no error message, instead npm gladly installs two versions of react at the same time which causes an obscure and hard to debug error at runtime. The workaround is to use npm-shrinkwrap but that is very annoying. It would be much better if reactfire would just support anything above 0.13.

The connection is really slow on react-native (ios)

For some reasons, it takes a long time for my react-native app to connect to firebase (i.e. receives the first event). Once the connection has been made, any subsequent events are triggered correctly with close to no latency.

Is there a reason why that would happen? (for example, Heroku sends dyno to sleep if no one uses them and spins them up when someone tries to access it. This means the first connection often takes much longer than the subsequent one)

API for responding to errors

I occasionally see this sort of thing being console.warn()-ed when using the Hacker News API, which results in my app displaying a loading indicator until the content in question is deleted or becomes available.

"FIREBASE WARNING: on() or once() for /v0/item/8477507 failed: Error: permission_denied: Client doesn't have permission to access the desired data. "

I can see that it's the Firebase library itself doing it, but it doesn't seem to have an API for error handling - I'd expect to be able to do an on('error', callback) or similar.

I can't pick out a way to catch errors from the minified Firebase code. Is there API for this, or are there any plans to add error handling?

Blinking/Uncatching Behaviour

I'm using this repository with a react application with react router, and what I've found is that it has a problem regarding blinking before things actually start loading; that makes sense because it's the time that it takes the request to be performed to the update the state.

Also if I have no connection during an operation it will just, never work; it will not even seek for old data in that was already used.

I have a proposal, I could make a PR for it in which I'd use mozilla's localForage library to store objects, being in, IndexedDB, WebSQL or even localStorage; and use them to populate the element rather than firebase itself.

Eg. in browsers that support IndexedDB the flow will be
Firebase -> IndexedDB -> ReactFire

If for some reason it's disconnected
Firebase -/-> IndexedDB -> ReactFire

IndexedDB will keep serving ReactFire, and will avoid blinking if resources have not changed as it'll be pretty fast accesible, the app will keep working even without internet unless a resource that has not been catched is asked for, load times of pages will be basically none and it'll sync first with the local and then with the remote. In very old browsers that don't even have localStorage, then it'll work as normal.

Precaching previous using a resource will be also possible, and of course, deleting resources from the local. eg.

ReactFire.catch(myRef)
ReactFire.delete(myRef)

//or

ReactFire.catch('/documents/-123124dkfasd')
ReactFire.delete('/documents/-123124dkfasd')

In the case of browsers with no support this function will do absolutely nothing.

once in a component I do.

this.bindAsObject(myRef,'value')

I'll get, in fact; the value stored in my IndexedDB, WebSQL; database, rather than directly from firebase, and any update done by firebase inside those storages will cause my element to update, in fact, it'll be totally backwards compatible.

Without support of those storages it'll work just as designed now.

There are several considerations with this, and it's that the product will be somewhat bigger and it'll have dependencies.

Also for some reason I can't get how your source code is structured, it seems like it's already processed by browserfy or the like; is there any original source code?

shouldComponentUpdate nextState always equals this.state

Been running into any issue where the shouldComponentUpdate function's nextState param is always equal to this.state making it impossible to see what data changed.

I managed to fix this issue by modifying reactfire to always clone this.data before calling setState:

this.setState( JSON.parse(JSON.stringify(this.data)) );
//this.setState(this.data);

To be honest, I'm not exactly sure why this worked.. maybe someone else can see what the issue is and propose a better solution.

Hi, please i need help with this. "_firebase2.default is not a constructor"

i got this error when i run my react App:

create.js?84fe:13 Uncaught TypeError: _firebase2.default is not a constructor

just in the line when a create a new Firebase:

const ref = new Firebase('https://my-project.firebaseio.com/');

Can any one help me please, i use the latest version of firebase, reactfire, react-mixin

componentDidUpdate not being called sometimes.

sometimes during componentWillMount (specially if the data has already been loading and you are moving across the history) a state is provided, this state contains no firebase references...

componentWillMount(){
    this.bindAsObject(window.APP.R.options.firebaseRef.child('request'),'request');

    //Maybe it's sync and it updated the state? somehow?
    if (this.state.request){
        this.getXtras();
    }
    console.log(this.state);
}
getXtras(){
    this.bindAsObject(window.APP.R.options.firebaseRef.child('xtras')
        .child(this.state.request.xtrasId),'xtras');
}
componentDidUpdate(prevProps,prevState){
   if (!prevState['request'] && this.state.request){
      this.getXtras();
   }
}

The state is {} , because no request is yet loaded.

Inmediatly after componentWillMount the render happens.

render(){
    console.log(this.state);
    ...
}

now my state is {'request':...} that means that somehow the request got a value set so fast that it wasn't caught by the componentDidUpdate function, so I could never load my xtras.

I believe that it's doing a setState synchronously, but I'm never sure if the value was set and or/how it was set.

Maybe what you should do is that:

componentWillMount(){
    let request = this.bindAsObject(window.APP.R.options.firebaseRef.child('request'),'request');

    //Maybe it's sync and it updated the state? somehow?
    if (request){
        this.getXtrasFor(request)
    }
    console.log(this.state);
}
componentDidUpdate(prevProps,prevState){
   if (!prevState['request'] && this.state.request){
      this.getXtrasFor(this.state.request);
   }
}

This is a pretty terrible problem, and the patch (to put setState in render with a timeout) is very much antipattern and damages the quality of the code.

Not supported anymore?

Rhis implementation uses mixins which are not recommended by react anymore. There has been no updates for while as well.
Could you please outline if there areany plans to move this lib further and what alternatives could you recommend

Add the Firebase key to array items

Currently, there is no way to get the Firebase key (aka push ID) for items bound via bindAsArray(). We should adopt a solution like AngularFire's $toJSON() method which handles both arrays of objects and arrays of primitives. In the case of objects, we do something very similar to what you have done. In the case of a primitive, we set the array items as objects with $value (i.e. the primitive value) and $id (the Firebase key).

this.bindAsArray() incorrectly concatenates data

I started using Reactfire 0.5.0 and when i bindAsArray(). my data comes back concat like this.
My Firebase data -
jakelingwall
He: "guy"
Her: "girl"

My function -
componentDidMount: function(){
this.ref = new Firebase("https://githubnote-taker.firebaseio.com");
var childRef = this.ref.child(this.getParams().username);
this.bindAsArray(childRef,"notes");
}

The array i get back ["guyhe","girlher"] but when i revert to reactfire 0.4.0 i get the correct array ["guy","girl"]

Compatibility with redux

No sure if this is right way to go ahead but any support for redux + firebase would be great. Currently reactfire starts listening in component. Redux will change it.

After redux, every component will dispatch an action (to subscribe/unsubscribe) to firebase and get notified when store changes. That way many components may get cached data which store already has before subscribing (for further changes) - this will remove flicker in UI.

Array can return items in the wrong order

Since bindAsArray() uses the value callback and then we loop through the keys of the object to add them to the array, there is no guarantee of the order of the elements in the array? This is not correct. We should either (1) make use of the DataSnapshot.forEach() method to properly iterate over the snapshot in order or (2) make use of the child_added, child_removed, and child_changed events instead of the value event. I think (1) makes sense in the short term and (2) makes the most sense in the long term. We should be able to get some performance benefits by doing (2) since then we won't be recreating so many records over and over every time an item is added to the array.

API keys are exposed to clients when code is pushed to production

Test case

When we run the sample apps in the browser and the API keys are exposed.

Steps to reproduce

Open the sample app in browser.
https://reactfiretodoapp.firebaseapp.com/
The click view source.

Expected behavior

Should not show any api-keys

Actual behavior

Its shows the following.

  <!-- Initialize the Firebase SDK -->
    <script>
      var config = {
        apiKey: "AIzaSyCdxGmqWURL8YUfGPK3OVANsyvsE0cHV5s",
        authDomain: "reactfiretodoapp.firebaseapp.com",
        databaseURL: "https://reactfiretodoapp.firebaseio.com"
      };
      firebase.initializeApp(config);
    </script>

not working with react native

I'm not sure what's wrong but basically it's not synching data, and doesn't say that anything is wrong.

The stackoverflow question

the version is 0.5.1

my code

if you want I can send you the link for firebase database as well

thanks

[0.5.0] Firebase.update failed: First argument contains an invalid key (.key) in property

I'm probably missing something obvious here but after upgrading to 0.5.0, when trying to update an existing record, I get Uncaught Error: Firebase.update failed: First argument contains an invalid key (.key) in property 'news.-XXXXXXXXXX'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]" from firebase-web.js:129 (v2.2.7)

This used to work in 0.4.0.

I'm loading the news item with;

var ref = new Firebase("https://XXXXXXXXXX.firebaseio.com/news/" + newsItemId);
this.bindAsObject(ref, "newsItem");

and updating the item with;

this.firebaseRefs["newsItem"].update(newsItem);

One of the changes in 0.5.0 was "ReactFire now adds the .key attribute to every record it creates via the bindAsArray() and bindAsObject() methods."

Of course I can do delete newsItem[".key"]; before updating the item but surely that cannot be the solution? :)

Creating a new item still works since it does not contain the new ReactFire ".key" property and the ReactFire Todo and Comment Box examples never update an existing item so they never experience this error.

support the container component pattern

A big part of the ReactJS community is moving from using mixins to using container components, and composing them together. I'd like to propose a createFirebaseContainer function (or possibly just createContainer, which would work as follows:

createFirebaseContainer(component, refs);

arguments

  • Component: The component you want to wrap
  • refs: a FirebaseRefs (see below) object or function that returns such anobject

If refs is a function, it should take in the props that were passed to the container when rendered, and returns a FirebaseRefs object.

The FirebaseRefs object

A FirebaseRefs object, is an object that looks like this:

{
  "<propName>": {
    "ref": DatabaseRef,
    "type": "array" | "object",
  }
  ...
}

Here, "<propname>" is the name of a property you want to receive.
ref should be the database reference you want to bind that property to.
typeshould be either "array" or "object" depending on whether you want to bind to that reference as an array or an object.

Example Usage

Here's an example for a TodoList component:

const TodoList = React.createClass({
  render(){
    return <ul>
      {this.props.todos.map((todo) => {
        return <li><input type="checkbox" defaultChecked={todo.done}> {todo.text}</li>
      })}
    </ul>
  }
});

export default createFirebaseContainer(TodoList, {
  todos:  {
    ref: firebase.database().ref("/todos"),
    type: "array"
  }
});

Now, when you render the exported component, it would receive a todos prop, which represents the value in the database at /todos. When the value changes, the component is automatically re-rendered.

Using a function for refs

You may not know in advance where the data you need lives. For example, a TodoList will likely only want to show todos for a specific user. These items could live at /todos/{userID}. To make it easier to specify the refs at runtime, you can pass a function like this:

const TodoList = function(props) {
  return <ul>
    {props.todos.map((todo) => {
      return <li><input type="checkbox" defaultChecked={todo.done}> {todo.text}</li>
    })}
  </ul>
};

export default createFirebaseContainer(TodoList, (props) => {
  return {
    todos:  {
      ref: firebase.database().ref("/todos/" + props.userID),
      type: "array"
    }
  }
});

Now, assuming we import the exported component as TodoList, we can render it as <TodoList userID="123abc" />, and the todos for that user would be fetched.

Advantages

The big advantage for this approach, is that we support more types of components. We don't rely on the component having state,, so we can write functional components, as seen above. We don't rely on the component having mixins, so we can support ES6 classes.

This also aligns it more with other popular libraries in the React ecosystem, such as Relay's createContainer, and react-redux's connect (though it uses a somewhat diffeent way of calling the function).

I'm willing to create a PR for this.

Add support for authentication

I'm fairly new at React, so this could be the wrong design entirely, but:

It looks like a good way to handle authentication is to write:

componentWillMount() {
  firebaseRef.onAuth(auth => this.setState({auth: auth}));
},
componentWillUnmount() {
  firebaseRef.offAuth(...);
},

It would be nice if ReactFire would handle dropping the current authentication state into a component's state, instead of needing this custom code.

Reactfire do not bind correctly

Well, I don't know if the problem is with Reactfire or I am doing something wrong...
here is what I got:

I have this component

var ChatList = React.createClass({
  mixins: [ReactFireMixin],
  displayName: 'ChatList',
  getInitialState: function() {
    return { messages: []};
  },
  render: function() {
    var messages = this.state.messages.map(function (message, index) {
      return(
        <Post message={ message } key={ index }>
        </Post>
      );
    });

and I bind data from firebase with

  componentDidMount: function() {
    var db = firebase.database().ref("messages/" + this.props.room.uid);
    this.bindAsArray(db, "messages");

at this point, nothing was rendered in the page, so I decide to take a look on what the messages state had inside, and got something weird, it was something like

Object {.value: "{"createdAt":1466963340426,"room":{"createdAt":144โ€ฆ=3","firebase_token":""},"uid":"b49UXigwuoe0djz"}", .key: "b49UXigwuoe0djz"}

inside Post class, I have

var Post = React.createClass({
  render: function () {
    return (
      <li key={ this.props.message.uid }>
        <div className="avatar">
          <img src={ this.props.message.sender.avatar }/>
        </div>
        <div className="messages">
          <p>{ this.props.message.content }</p>
          <span className="date">{ "@"+this.props.message.sender.nickname + " โ€ข " }</span>
          <span className="date" data-livestamp={ this.props.message.createdAt/1000 }>

          </span>
        </div>
      </li>
      )
  }
});

and of course, I got a lot of Cannot read property 'avatar' of undefined for example.
Seems like the object returned in the bind is not really a json, but somehow an array (or am I wrong).

I made it work, changing the componentDidMount to

    db.limitToLast(25).orderByValue().on('value', function(dbMessages) {
      var messages = [];
      dbMessages.forEach(function(m) {
        var item = m.val();
        item['.key'] = m.key;
        messages.push(JSON.parse(item));
        scrollChatRoom();
      }.bind(this));

      this.setState({
        messages: messages
      });
    }.bind(this));
  },

although it seems a "workaround". So is it a bug or am I doing something wrong?

Provide a way to bind to a props-dependent ref

This has come up in a couple questions (#31, #49, http://stackoverflow.com/q/32688547/943619), so I'm going to attempt to propose an API change to fix it. I'd be totally happy with another solution, of course.

I want to bind a dynamic Firebase reference to this.state.foo. We want to recompute the reference whenever props change (*). If the reference hasn't changed, we don't want any extra network traffic, as seems to happen when fbref.off(); fbref.on() are called. If the reference has changed, it'd be nice to avoid the flicker from an intermediate this.setState({foo: undefined}) as happens in unbind().

So, bindAsObject() and bindAsArray() should accept a function (props)=>ref as their first parameter, in addition to the existing Firebase ref. (That is, bindAsX(functionOrRef, name, callback).) This should be called at bind time with this.props, and again in componentWillReceiveProps. If it returns the same ref as the previous call, nothing should happen. If it returns a new ref, ReactFire should unbind from the old reference and bind to the new one. ReactFire should not set the state to undefined while the new data loads, to avoid making the UI jump twice. Optionally, ReactFire should set a "loading" state of some sort so the UI can grey-out or otherwise disable the right regions of the component while it's out of date.

(*) In general, the reference could be dynamic based on both state (especially auth data from #65) and props, but restricting it to props makes sure data only flows in one direction, and state can always(?) be turned into props by nesting an extra level.

Impossible to rebind on propsDidUpdate

I want to use react-router which does not rebuild the components if you simply change a :recordId token in the url. This is making it difficult for me because I'm trying to use this mixin to handle a lot of the firebase heavy lifting but I'm binding to a URL based on the route token.

Do you suggestion I just bind to the base of my application (which makes me concerned that I will be subscribing to events and updates other users make on sections of the that I don't care about) or is there a way to 'adjust' the binding after-the-fact?

Why '.key' and '.value'?

Just wanted to know why the use of '.key' and '.value' rather than just 'key' & 'value'. Also why does reactfire bind work like:

[
  {
    ".key": "-Jtjl482BaXBCI7brMT8",
    ".value": 100
  },
  {
    ".key": "-Jtjl6tmqjNeAnQvyD4l",
    "first": "Fred",
    "last": "Flintstone"
  },
  {
    ".key": "-JtjlAXoQ3VAoNiJcka9",
    ".value": "foo"
  }
]

instead of just:

[
  {
    "-Jtjl482BaXBCI7brMT8" : 100
  },
  {
    "-Jtjl6tmqjNeAnQvyD4l": { 
       "first": "Fred",
       "last": "Flintstone"
      }
  },
  {
    "-JtjlAXoQ3VAoNiJcka9" : "foo"
  }
]

What is the plan for moving to ES6?

React is phasing out mixins with the change to ES6 classes. What is the plan for the reactfire mixin with this coming change? Could reactfire also tie in with react contexts? Below is a link to the context approach:

https://blog.jscrambler.com/react-js-communication-between-components-with-contexts

React relay with graphql is another approach coming to react. It would seem like reactfire updated to work with ES6 classes and the context approach might be a powerful alternative to relay with added collaboration! It might also work to incorporate some of the graphql as well?

Discussion List

Is there a discussion list for reactfire? If there is it would be nice to have a link to it in the repo.

Question Regarding Joins

Hi,

Nice plugin.

I have a question: I know that you are supposed to pass a reference of the tree in order to work. How can I pass a reference of the related tree? For example I have data like so:

"orders": { "1": { "createdAt": 1459361875337, "updatedAt": 1459361875337, "status": 2 } }, "orderDetails": { "1": { "total": 42, "paymentMathod": "Cash On Delivery" }, "2": { "total": 42, "paymentMathod": "Cash On Delivery" } },

Order is connected to orderDetails by the key. How would grab the orderDetails reference according to the order and bind it to state?

Thanks

React Firebase 3 Issue!

Hi,

I keep getting this error with the new SDK whenever I call Firebase functions
screen shot 2016-05-19 at 6 24 25 pm
Does the new SDK work on React?

Thank You!

Remove items

Thanks for these examples, they're super helpful to study.

Most todo apps have a method to remove items, and I'm having a hard time figuring out how to do this with reactfire. Is this something that could be added to the examples? Or could you point me in the right direction and I'll create a pull request?

Thanks for any time you can spare on this.

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.