|
2 | 2 | var React = require('react');
|
3 | 3 | var api = require('../utils/api');
|
4 | 4 | var Link = require('react-router').Link;
|
| 5 | +var NewContactForm = require('../components/NewContactForm'); |
| 6 | +var ContactStore = require('../stores/ContactStore'); |
5 | 7 |
|
6 | 8 | var Root = module.exports = React.createClass({
|
7 | 9 |
|
8 | 10 | statics: {
|
9 | 11 | getRouteProps: function() {
|
10 |
| - var preloadedData = ENV.CLIENT && window.ROUTER_PROPS.root; |
11 |
| - return preloadedData || { |
12 |
| - contactData: api.get('/contacts') |
| 12 | + return { |
| 13 | + contacts: ContactStore.getAll() |
13 | 14 | };
|
14 | 15 | }
|
15 | 16 | },
|
16 | 17 |
|
| 18 | + getInitialState: function() { |
| 19 | + return { |
| 20 | + contacts: this.props.contacts |
| 21 | + }; |
| 22 | + }, |
| 23 | + |
| 24 | + componentWillReceiveProps: function(newProps) { |
| 25 | + // because we have to put it on state, we have to get the new props |
| 26 | + this.setState({contacts: newProps.contacts}); |
| 27 | + }, |
| 28 | + |
17 | 29 | renderContacts: function() {
|
18 |
| - if (!this.props.contactData) return null; |
19 |
| - var contacts = this.props.contactData.contacts; |
| 30 | + if (!this.props.contacts) |
| 31 | + return null; |
| 32 | + |
| 33 | + var contacts = this.state.contacts.records; |
20 | 34 | return contacts.map(function(contact) {
|
21 | 35 | return <li key={contact.id}>
|
22 | 36 | <Link to="contact" params={{id: contact.id}}>{contact.first} {contact.last}</Link>
|
23 | 37 | </li>;
|
24 | 38 | });
|
25 | 39 | },
|
26 | 40 |
|
| 41 | + componentDidMount: function() { |
| 42 | + ContactStore.addChangeListener(this.handleContactsChange); |
| 43 | + }, |
| 44 | + |
| 45 | + componentWillUnmount: function() { |
| 46 | + ContactStore.removeChangeListener(this.handleContactsChange); |
| 47 | + }, |
| 48 | + |
| 49 | + handleContactsChange: function() { |
| 50 | + this.setState({contactData: ContactStore.getAll()}); |
| 51 | + }, |
| 52 | + |
27 | 53 | render: function() {
|
28 | 54 | return (
|
29 | 55 | <div>
|
30 | 56 | <h1>Address Book</h1>
|
| 57 | + <NewContactForm/> |
31 | 58 | <ul>
|
32 | 59 | {this.renderContacts()}
|
33 | 60 | </ul>
|
|
0 commit comments