@@ -4,16 +4,38 @@ var ShowAddButton = require('./ShowAddButton');
44var FeedForm = require ( './FeedForm' ) ;
55var FeedList = require ( './FeedList' ) ;
66var _ = require ( 'lodash' ) ;
7+ var Firebase = require ( 'firebase' ) ;
78
89var Feed = React . createClass ( {
10+
11+ loadData : function ( ) {
12+ var ref = new Firebase ( 'https://react-voting.firebaseio.com/feed' ) ;
13+ ref . on ( 'value' , function ( snapshot ) {
14+ var items = [ ] ;
15+ var sorted = [ ] ;
16+
17+ snapshot . forEach ( function ( itemSnapshot ) {
18+ var item = itemSnapshot . val ( ) ;
19+ item . key = itemSnapshot . key ( ) ;
20+ items . push ( item ) ;
21+ } ) ;
22+
23+ sorted = _ . sortBy ( items , function ( item ) {
24+ return - item . voteCount ;
25+ } ) ;
26+
27+ this . setState ( {
28+ items : sorted
29+ } ) ;
30+ } . bind ( this ) ) ;
31+ } ,
32+
33+ componentDidMount : function ( ) {
34+ this . loadData ( ) ;
35+ } ,
936 getInitialState : function ( ) {
10- var FEED_ITEMS = [
11- { key : '1' , title : 'Realtime data!' , description : 'Firebase is cool!' , voteCount : 49 } ,
12- { key : '2' , title : 'Javascipt is fun' , description : 'Javascript feature here!' , voteCount : 34 } ,
13- { key : '3' , title : 'Coffee makes you awake' , description : 'A coffee pro here!' , voteCount : 25 }
14- ] ;
1537 return {
16- items : FEED_ITEMS ,
38+ items : [ ] ,
1739 formDisplayed : false
1840 }
1941 } ,
@@ -22,29 +44,17 @@ var Feed = React.createClass({
2244 * @param newItem {Object} Item to be added
2345 */
2446 onNewItem : function ( newItem ) {
25- var newItems = this . state . items . concat ( [ newItem ] ) ;
26- this . setState ( {
27- items : newItems ,
28- formDisplayed : false ,
29- key : this . state . items . length
30- } ) ;
47+ var ref = new Firebase ( 'https://react-voting.firebaseio.com/feed' ) ;
48+ ref . push ( newItem ) ;
3149 } ,
3250 onToggleForm : function ( ) {
3351 this . setState ( {
3452 formDisplayed : ! this . state . formDisplayed
3553 } ) ;
3654 } ,
3755 onVote : function ( item ) {
38- var items = _ . uniq ( this . state . items ) ;
39- var index = _ . findIndex ( items , function ( feedItems ) {
40- return feedItems . key === item . key ;
41- } ) ;
42- var oldObject = items [ index ] ;
43- var newItems = _ . pull ( items , oldObject ) ;
44- newItems . push ( item ) ;
45- this . setState ( {
46- items : newItems
47- } ) ;
56+ var ref = new Firebase ( 'https://react-voting.firebaseio.com/feed' ) . child ( item . key ) ;
57+ ref . update ( item ) ;
4858 } ,
4959 render : function ( ) {
5060 return (
0 commit comments