forked from atom/github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserve-model.js
61 lines (49 loc) · 1.51 KB
/
observe-model.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
import React from 'react';
import PropTypes from 'prop-types';
import ModelObserver from '../models/model-observer';
export default class ObserveModel extends React.Component {
static propTypes = {
model: PropTypes.shape({
onDidUpdate: PropTypes.func.isRequired,
}),
fetchData: PropTypes.func.isRequired,
fetchParams: PropTypes.arrayOf(PropTypes.any),
children: PropTypes.func.isRequired,
}
static defaultProps = {
fetchParams: [],
}
constructor(props, context) {
super(props, context);
this.state = {data: null};
this.modelObserver = new ModelObserver({fetchData: this.fetchData, didUpdate: this.didUpdate});
}
componentDidMount() {
this.mounted = true;
this.modelObserver.setActiveModel(this.props.model);
}
componentDidUpdate(prevProps) {
this.modelObserver.setActiveModel(this.props.model);
if (
!this.modelObserver.hasPendingUpdate() &&
prevProps.fetchParams.length !== this.props.fetchParams.length ||
prevProps.fetchParams.some((prevParam, i) => prevParam !== this.props.fetchParams[i])
) {
this.modelObserver.refreshModelData();
}
}
fetchData = model => this.props.fetchData(model, ...this.props.fetchParams);
didUpdate = () => {
if (this.mounted) {
const data = this.modelObserver.getActiveModelData();
this.setState({data});
}
}
render() {
return this.props.children(this.state.data);
}
componentWillUnmount() {
this.mounted = false;
this.modelObserver.destroy();
}
}