forked from benmvp/react-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
88 lines (75 loc) · 2.31 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import EmailList from './components/EmailList';
import EmailView from './components/EmailView';
import EmailForm from './components/EmailForm';
export default class App extends PureComponent {
static propTypes = {
pollInterval: PropTypes.number
};
static defaultProps = {
// default the `pollInterval` prop to 2 secs when not specified
pollInterval: 2000
};
state = {
// Initialize emails state to an empty array.
// Will get populated with data in `componentDidMount`
emails: [],
// Initialize selected email ID to -1, indicating nothing is selected.
// When an email is selected in EmailList, this will be updated to
// corresponding ID
selectedEmailId: -1
};
componentDidMount() {
// Retrieve emails from server once we know DOM exists
this._getUpdateEmails();
// Set up long-polling to continuously get new data
this._pollId = setInterval(
() => this._getUpdateEmails(),
this.props.pollInterval
);
}
componentWillUnmount() {
// Need to remember to clearInterval when the component gets
// removed from the DOM, otherwise the interval will keep going
// forever and leak memory
clearInterval(this._pollId);
}
_getUpdateEmails() {
return fetch('//localhost:9090/emails')
.then(res => res.json())
.then(emails => this.setState({emails}))
.catch(ex => console.error(ex));
}
_handleItemSelect(selectedEmailId) {
// update state (so that the EmailView will show)
this.setState({selectedEmailId});
}
_handleEmailViewClose() {
// We close the email view by resetting the selected email
this.setState({selectedEmailId: -1});
}
render() {
let {emails, selectedEmailId} = this.state;
let selectedEmail = emails.find(email => email.id === selectedEmailId);
let emailViewComponent;
if (selectedEmail) {
emailViewComponent = (
<EmailView
email={selectedEmail}
onClose={this._handleEmailViewClose.bind(this)}
/>
);
}
return (
<main className="app">
<EmailList
emails={emails}
onItemSelect={this._handleItemSelect.bind(this)}
/>
{emailViewComponent}
<EmailForm />
</main>
);
}
}