-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataLoader.mjs
More file actions
61 lines (50 loc) · 1.36 KB
/
Copy pathdataLoader.mjs
File metadata and controls
61 lines (50 loc) · 1.36 KB
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
import createSubscription from "./createSubscription.mjs";
const PENDING = 0;
export const RESOLVED = 1;
export const REJECTED = 2;
/**
* Looks up or creates a new cache reference.
* @ignore
* @kind function
* @name dataLoader
* @param {CacheKey} key The cache key.
* @param {Function} asyncFn An asynchronous function that returns data.
* @param {DataCache} dataCache A data cache.
* @returns {CacheReference} A cache reference.
*/
export default function dataLoader(key, asyncFn, dataCache) {
const subscription = createSubscription();
let reference = dataCache.get(key);
if (reference && reference.state === PENDING) {
return reference;
}
reference = {
loadOnMount: false,
key,
load() {
if (reference.state === PENDING) {
return;
}
const thenable = asyncFn(key);
reference.thenable = thenable;
reference.state = PENDING;
return thenable
.then((response) => {
reference.state = RESOLVED;
reference.value = response;
})
.catch((error) => {
reference.state = REJECTED;
reference.value = error;
})
.then(() => {
subscription.notify();
dataCache.subscription.notify(key);
});
},
onUpdate: subscription.subscribe,
};
reference.load();
dataCache.set(key, reference);
return reference;
}