-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathwithStaticQuery.js
95 lines (81 loc) · 2.85 KB
/
withStaticQuery.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
89
90
91
92
93
94
95
import React from 'react';
import getDisplayName from './getDisplayName';
export default function withStaticQueryContainer(config) {
return function(WrappedComponent) {
/**
* We use it like this so we can have naming inside React Dev Tools
* This is a standard pattern in HOCs
*/
class GrapherStaticQueryContainer extends React.Component {
state = {
isLoading: true,
error: null,
data: [],
};
componentWillReceiveProps(nextProps) {
const { query } = nextProps;
if (!config.shouldRefetch) {
this.fetch(query);
} else if (config.shouldRefetch(this.props, nextProps)) {
this.fetch(query);
}
}
componentDidMount() {
const { query, config } = this.props;
this.fetch(query);
if (config.pollingMs) {
this.pollingInterval = setInterval(() => {
this.fetch();
}, config.pollingMs);
}
}
componentWillUnmount() {
this.pollingInterval && clearInterval(this.pollingInterval);
}
fetch(query) {
if (!query) {
query = this.props.query;
}
query.fetch((error, data) => {
if (error) {
this.setState({
error,
data: [],
isLoading: false,
});
} else {
this.setState({
error: null,
data,
isLoading: false,
});
}
});
}
refetch = () => {
const { loadOnRefetch = true } = config;
const { query } = this.props;
if (loadOnRefetch) {
this.setState({ isLoading: true }, () => {
this.fetch(query);
});
} else {
this.fetch(query);
}
};
render() {
const { config, props, query } = this.props;
return React.createElement(WrappedComponent, {
grapher: this.state,
config,
query,
props: { ...props, refetch: this.refetch },
});
}
}
GrapherStaticQueryContainer.displayName = `StaticQuery(${getDisplayName(
WrappedComponent,
)})`;
return GrapherStaticQueryContainer;
};
}