-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePreloadedData.mjs
More file actions
49 lines (43 loc) · 1.23 KB
/
usePreloadedData.mjs
File metadata and controls
49 lines (43 loc) · 1.23 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
import { useEffect, useReducer, useState } from "react";
import { REJECTED, RESOLVED } from "./dataLoader.mjs";
/**
* usePreloadedData Options
* @kind typedef
* @name UsePreloadedDataOptions
* @type {object}
* @prop {boolean} reloadOnMount Disable reloading on mount.
*/
/**
* Access preloaded data, suspends if data is unavailable.
* @kind function
* @name usePreloadedData
* @param {CacheReference} reference A cache reference.
* @param {UsePreloadedDataOptions} userOptions User configurable options.
* @throws {Promise|string}
* @returns {*} The cached value
*/
export default function usePreloadedData(reference, userOptions = {}) {
const [options] = useState(userOptions);
const [, forceUpdate] = useReducer((x) => {
return x + 1;
}, 0);
useEffect(() => {
return reference.onUpdate(() => {
forceUpdate();
});
}, [reference]);
useEffect(() => {
if (reference.loadOnMount && options.reloadOnMount !== false) {
reference.load();
}
return () => {
reference.loadOnMount = true;
};
}, [reference, options]);
if (reference.state === RESOLVED) {
return reference.value;
} else if (reference.state === REJECTED) {
throw reference.value;
}
throw reference.thenable;
}