forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ReactDataFetch.js
93 lines (83 loc) · 2.09 KB
/
ReactDataFetch.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Wakeable} from 'shared/ReactTypes';
import {readCache} from 'react/unstable-cache';
const Pending = 0;
const Resolved = 1;
const Rejected = 2;
type PendingResult = {|
status: 0,
value: Wakeable,
|};
type ResolvedResult = {|
status: 1,
value: mixed,
|};
type RejectedResult = {|
status: 2,
value: mixed,
|};
type Result = PendingResult | ResolvedResult | RejectedResult;
const fetchKey = {};
function readResultMap(): Map<string, Result> {
const resources = readCache().resources;
let map = resources.get(fetchKey);
if (map === undefined) {
map = new Map();
resources.set(fetchKey, map);
}
return map;
}
// TODO: options, auth, etc.
export function fetch(url: string): Object {
const map = readResultMap();
const entry = map.get(url);
if (entry === undefined) {
let resolve = () => {};
const wakeable: Wakeable = new Promise(r => {
// TODO: should this be a plain thenable instead?
resolve = r;
});
const result: Result = {
status: Pending,
value: wakeable,
};
map.set(url, result);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
// TODO: should we handle status codes?
if (result.status !== Pending) {
return;
}
const resolvedResult = ((result: any): ResolvedResult);
resolvedResult.status = Resolved;
resolvedResult.value = xhr.response;
resolve();
};
xhr.onerror = function() {
if (result.status !== Pending) {
return;
}
const rejectedResult = ((result: any): RejectedResult);
rejectedResult.status = Rejected;
// TODO: use something else as the error value?
rejectedResult.value = xhr;
resolve();
};
xhr.open('GET', url);
xhr.send();
throw wakeable;
}
const result: Result = entry;
if (result.status === Resolved) {
return result.value;
} else {
throw result.value;
}
}