-
Notifications
You must be signed in to change notification settings - Fork 0
/
useFetch.ts
64 lines (46 loc) · 1.37 KB
/
useFetch.ts
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
import { cache } from './cache';
/*
useFetch will fire its callback function twice:
1) first, with cached data,
2) then with new data;
*/
export function useFetch({
url = '',
query = '',
callback = function doCallback(data: any) {
console.log('error: useFetch requires a callback function');
},
useCache = true,
}) {
/*
first, check if we have a cached response to this query.
if so, pass that response to our callback function
*/
const cached = JSON.parse(cache.retrieve(query));
if (cached.data && useCache) {
callback(cached);
}
/*
then, do a fetch request to grab the latest response.
pass the latest response to our callback function,
and cache the latest response.
*/
async function doFetch() {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: query,
});
const data = await response.json();
// if the new data is the same as the old, then do nothing
if (JSON.stringify(data) === JSON.stringify(cached) && useCache) {
return;
}
callback(data);
cache.save(query, JSON.stringify(data));
}
doFetch();
}