Reputation: 2520
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"
};
firebase.initializeApp(config);
var App = React.createClass({
...,
getInitialState(){ //... },
componentWillMount(){
var ref = firebase.database().ref("items");
this.bindAsObject(ref, "items");
ref.on('value', this.handleDataLoaded);
},
render: function() {
return (
<div>
...
<Header itemsStore={this.firebaseRefs.items}/>
...
</div>
)
}
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
componentWillMount(){
var ref = firebase.database().ref().child("items/" + this.props.item.key);
this.bindAsObject(ref, "item");
},
handleDoneChange(event){
console.log(this.state.item); // --------------------> Object {done: false, text: "second task", .key: "-KOlfbvw52_47CYiLlxr"}
this.setState({done:event.target.checked});
this.state.item.update({done: event.target.checked}); // --> is not a function
},
Any working examples out there?
Upvotes: 0
Views: 739
Reputation: 599081
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');;
firebaseRef.child(key).remove();
},
JSX:
<TodoList2 items={ this.state.items } removeItem={ this.removeItem } />
In your code the code for the update could simply be:
handleDoneChange(key){
var ref = firebase.database().ref().child("items/")
ref.child(key).update({done: event.target.checked});
},
Upvotes: 1