-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetchHOC.js
98 lines (83 loc) · 2.19 KB
/
fetchHOC.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
96
97
98
// @flow
import React, { Component } from "react";
import { connect } from "react-redux";
import autobind from "class-autobind";
import { fetchData, voidFunction } from "./helpers";
type Props = {
fetchedData: Object,
dispatch: (action: Object) => void,
data?: Object,
state: Object
};
type State = {
isLoading: boolean,
isSuccess: ?boolean
};
export default (
url: string,
mapFromState: Function,
mapFromProps: Function
) => (Instance: Object) => {
class Fetcher extends Component {
state: State;
props: Props;
_endpoint: ?string;
constructor() {
super(...arguments);
this.state = {
isLoading: true,
isSuccess: null
};
autobind(this);
}
componentDidMount() {
this._fetchData();
}
render() {
let { ...rest } = this.props;
let { isLoading, isSuccess } = this.state;
let data = this._getFetchedData();
return (
<Instance
{...rest}
data={data}
isLoading={isLoading}
isSuccess={isSuccess}
refetch={this._fetchData}
/>
);
}
_fetchData() {
fetchData.call(this, this._getEndpoint());
}
_getFetchedData() {
let { state } = this.props;
let currFetchedData = state.__FETCHER__[this._getEndpoint()];
return this._combineFetchedData(currFetchedData);
}
_getEndpoint() {
return this._endpoint || this._mapToEndpoint();
}
_mapToEndpoint() {
let { state } = this.props;
let mapping = { ...mapFromState(state), ...mapFromProps(this.props) };
let endpoint = Object.keys(mapping).reduce((result, variable) => {
return result.replace(variable, mapping[variable]);
}, url);
return endpoint;
}
_combineFetchedData(currFetchedData: Object) {
let { data } = this.props;
let prevFetchedData = data;
if (prevFetchedData) {
return Array.isArray(data)
? [currFetchedData, ...data]
: [currFetchedData, data];
}
return currFetchedData;
}
}
mapFromState = mapFromState || voidFunction;
mapFromProps = mapFromProps || voidFunction;
return connect(state => ({ state }))(Fetcher);
};