-
-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathuse-resource.js
More file actions
70 lines (60 loc) · 1.58 KB
/
use-resource.js
File metadata and controls
70 lines (60 loc) · 1.58 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
62
63
64
65
66
67
68
69
70
import { useState, useEffect } from 'preact/hooks';
/**
* @typedef {Object} CacheEntry
* @property {Promise<any>} promise
* @property {'pending'|'success'|'error'} status
* @property {any} result
* @property {number} users
*/
/** @type {Map<string, CacheEntry>} */
export const CACHE = new Map();
export const createCacheKey = (fn, deps) => '' + fn + JSON.stringify(deps);
export function useResource(fn, deps) {
const update = useState({})[1];
const cacheKey = createCacheKey(fn, deps);
let state = CACHE.get(cacheKey);
if (!state) {
state = setupCacheEntry(fn, cacheKey, update);
}
useEffect(() => {
state.users++;
return () => {
// Delete cached Promise if nobody uses it anymore
if (state.users-- <= 0) {
CACHE.delete(cacheKey);
}
};
}, [cacheKey, state]);
if (state.status === 'success') return state.result;
else if (state.status === 'error') throw state.result;
throw state.promise;
}
/**
* @param {() => Promise<any>} fn
* @param {string} cacheKey
* @param {(state: CacheEntry) => void} [update]
* @returns {CacheEntry}
*/
export function setupCacheEntry(fn, cacheKey, update) {
/** @type {CacheEntry} */
const state = { promise: fn(), status: 'pending', result: undefined, users: 0 };
if (state.promise.then) {
state.promise
.then(r => {
state.status = 'success';
state.result = r;
})
.catch(err => {
state.status = 'error';
state.result = err;
})
.finally(() => {
update && update(state);
});
} else {
state.status = 'success';
state.result = state.promise;
}
CACHE.set(cacheKey, state);
return state;
}