-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathFetch.js
201 lines (167 loc) · 5.37 KB
/
Fetch.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import React, { useState, useEffect, useRef } from 'react';
import { parseBody, isFunction, isObject } from './utils';
import SimpleCache from './SimpleCache';
const FetchContext = React.createContext({});
function getOptions(options) {
return isFunction(options) ? options() : options;
}
function getCache(props) {
return props.cache === true
? new SimpleCache()
: isObject(props.cache)
? props.cache
: null;
}
function useMountedRef() {
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
return mountedRef;
}
function useFetch(props) {
const [state, setState] = useState({
request: {
url: props.url,
options: props.options
},
loading: props.manual ? null : true,
data: undefined,
error: undefined
});
state.fetch = doFetch;
state.clearData = () => setState({ ...state, data: undefined });
const cache = useRef(getCache(props)); // TODO: Update on cache prop change
const promises = useRef([]);
const mountedRef = useMountedRef();
const as = props.as || 'auto';
const fetchFunction =
props.fetchFunction || ((url, options) => fetch(url, options));
useEffect(() => {
if (isFunction(props.onChange)) {
// Clear the response even if we do not call doFetch immediately
props.onChange({ ...state, response: undefined });
}
if (props.url && !props.manual) {
doFetch(props.url, props.options);
}
}, [props.url, props.manual, ...(props.deps || [])]);
function doFetch(url, options, updateOptions) {
if (url == null) {
url = props.url;
}
options = getOptions(options || props.options);
const request = { url, options };
if (cache.current && cache.current.get(url)) {
// Restore cached state
const promise = cache.current.get(url);
promise.then(cachedState => update(cachedState, promise, updateOptions));
promises.current.push(promise);
} else {
update({ request, loading: true }, null, updateOptions);
const promise = fetchFunction(url, options)
.then(response => {
const dataPromise = isFunction(as)
? as(response)
: isObject(as)
? parseBody(response, as)
: as === 'auto'
? parseBody(response)
: response[as]();
return dataPromise
.then(data => ({ response, data }))
.catch(error => ({ response, data: error }));
})
.then(({ response, data }) => {
const newState = {
request,
loading: false,
[response.ok ? 'error' : 'data']: undefined, // Clear last response
[response.ok ? 'data' : 'error']: data,
response
};
update(newState, promise, updateOptions);
return newState;
})
.catch(error => {
// Catch request errors with no response (CORS issues, etc)
const newState = {
request,
data: undefined,
error,
loading: false
};
update(newState, promise, updateOptions);
// Rethrow so not to swallow errors, especially from errors within handlers (children func / onChange)
throw error;
return newState;
});
promises.current.push(promise);
if (cache.current) {
cache.current.set(url, promise);
}
return promise;
}
}
function update(nextState, currentPromise, options = {}) {
if (currentPromise) {
// Handle (i.e. ignore) promises resolved out of order from requests
const index = promises.current.indexOf(currentPromise);
if (index === -1) {
// Ignore update as a later request/promise has already been processed
return;
}
// Remove currently resolved promise and any outstanding promises
// (which will cause them to be ignored when they do resolve/reject)
promises.current.splice(0, index + 1);
}
const { onChange, onDataChange, onResponseChange } = props;
let data = undefined;
if (
nextState.data &&
nextState.data !== state.data &&
isFunction(onDataChange)
) {
data = onDataChange(
nextState.data,
options.ignorePreviousData ? undefined : state.data
);
}
if (
nextState.response &&
nextState.response !== state.response &&
isFunction(onResponseChange)
) {
data = onResponseChange(nextState.response);
}
if (isFunction(onChange)) {
// Always call onChange even if unmounted. Useful for `POST` requests with a redirect
onChange({
...state,
...nextState,
...(data !== undefined && { data })
});
}
// Ignore passing state down if no longer mounted
if (mountedRef.current) {
// If `onDataChange` prop returned a value, we use it for data passed down to the children function
setState({ ...state, ...nextState, ...(data !== undefined && { data }) });
}
}
return state;
}
const Fetch = ({ children, ...props }) => (
<FetchContext.Provider value={useFetch(props)}>
{isFunction(children) ? (
<FetchContext.Consumer>{children}</FetchContext.Consumer>
) : (
children
)}
</FetchContext.Provider>
);
Fetch.Consumer = FetchContext.Consumer;
export { useFetch, FetchContext };
export default Fetch;