-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwithDatascriptQuery.js
More file actions
104 lines (88 loc) · 2.81 KB
/
Copy pathwithDatascriptQuery.js
File metadata and controls
104 lines (88 loc) · 2.81 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import React from 'react';
import shallowEqual from './shallowEqual';
import datascript from 'datascript';
import parseQueryAttributes from './parseQueryAttributes';
export default ({ query, pull, rules, dbConn, initialParams }) =>
BaseComponent => {
return class extends React.Component {
static contextTypes = {
conn: React.PropTypes.object
};
static propTypes = {
entityIds: React.PropTypes.array,
params: React.PropTypes.array,
conn: React.PropTypes.object
};
constructor(props, context) {
super(props, context);
this.conn = props.conn || context.conn;
this.state = {
result: [],
params: props.params || initialParams,
parsedQueryAttrs: query ? parseQueryAttributes(query) : {}
};
}
componentWillMount() {
this.execQuery();
datascript.listen(this.conn, this.execQuery);
}
componentWillUnmount() {
datascript.unlisten(this.conn);
}
componentWillReceiveProps({ params }) {
if (!shallowEqual(params, this.props.params)) {
this.setParams(params);
}
}
setParams = (params) => {
this.setState({params}, this.execQuery);
}
execQuery = (report) => {
const { result, params, parsedQueryAttrs } = this.state;
if (report) {
const someQueryAttrChanged = report.tx_data
.map(({a}) => a)
.some(a => parsedQueryAttrs[a]);
//Did this last transaction not contain changes to any fields referenced
//by this query? Skip the re-query (and corresponding component update)
if (query && !someQueryAttrChanged) {
return;
}
}
if (query) {
const qArgs = [query, datascript.db(this.conn)];
if (params) {
qArgs.push(params);
}
if (rules) {
qArgs.push(rules);
}
let queryResult = datascript.q(...qArgs);
this.setState({ result: queryResult || this.state.result });
return;
}
if (pull) {
const { entityIds } = this.props;
let queryResult = datascript.pull_many(datascript.db(this.conn), pull, entityIds);
this.setState({ result: queryResult || this.state.result });
return;
}
if (dbConn) {
let queryResult = dbConn(this.conn);
this.setState({ result: queryResult || this.state.result });
}
}
transactData = (data, txMsg) => {
datascript.transact(this.conn, data, txMsg);
}
render() {
return (
<BaseComponent
result={this.state.result}
transact={this.transactData}
setParams={this.setParams}
/>
);
}
}
}