dwilbank dwilbank - 1 year ago 89
React JSX Question

React + Firebase v3 - how to get a 2nd reference to firebase to update a single item

I'm trying to learn React+Firebase (using reactfire) following a ToDo tutorial written for firebase v2.

Now using the new reactfire docs, I saw how to get a reference to the firebase v3 so that I can list and create todo items.

// app.jsx

var Firebase = require('firebase');
var Header = require('./header');

var config = {
apiKey: "...",
authDomain: "...firebaseapp.com",
databaseURL: "https://...firebaseio.com"


var App = React.createClass({

getInitialState(){ //... },

var ref = firebase.database().ref("items");
this.bindAsObject(ref, "items");
ref.on('value', this.handleDataLoaded);

render: function() {
return (
<Header itemsStore={this.firebaseRefs.items}/>

But now I want to do an update action on a single item, and am told I have to create a new ref to firebase using just that item's id.

Is this still true?

Here's what I tried based upon the docs.

// list-item.jsx

var ref = firebase.database().ref().child("items/" + this.props.item.key);
this.bindAsObject(ref, "item");

console.log(this.state.item); // --------------------> Object {done: false, text: "second task", .key: "-KOlfbvw52_47CYiLlxr"}
this.state.item.update({done: event.target.checked}); // --> is not a function

Any working examples out there?

Answer Source

To update a specific item, you will indeed need to get a reference to that specific item. You code for setting up that reference looks fine to me.

But you shouldn't have to call bindAsObject(), unless you are trying to show that specific object elsewhere in your UI. If you just want to update the data, you can simply update the database directly. The existing list of items in your UI will automatically reflect that update.

See this snippet from the TODO example for ReactFire:

removeItem: function(key) {
  var firebaseRef = firebase.database().ref('todoApp/items');;


<TodoList2 items={ this.state.items } removeItem={ this.removeItem } />

In your code the code for the update could simply be:

    var ref = firebase.database().ref().child("items/")
    ref.child(key).update({done: event.target.checked});