UNPKG

2.03 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = useThenable;
7
8var React = _interopRequireWildcard(require("react"));
9
10function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
11
12function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
14function useThenable(create) {
15 const [promise] = React.useState(create);
16 let initialState = [false, undefined]; // Check if our thenable is synchronous
17
18 promise.then(result => {
19 initialState = [true, result];
20 });
21 const [state, setState] = React.useState(initialState);
22 const [resolved] = state;
23 React.useEffect(() => {
24 let cancelled = false;
25
26 const resolve = async () => {
27 let result;
28
29 try {
30 result = await promise;
31 } finally {
32 if (!cancelled) {
33 setState([true, result]);
34 }
35 }
36 };
37
38 if (!resolved) {
39 resolve();
40 }
41
42 return () => {
43 cancelled = true;
44 };
45 }, [promise, resolved]);
46 return state;
47}
48//# sourceMappingURL=useThenable.js.map
\No newline at end of file