hook.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.useSidecar = void 0;
  4. var react_1 = require("react");
  5. var env_1 = require("./env");
  6. var cache = new WeakMap();
  7. var NO_OPTIONS = {};
  8. function useSidecar(importer, effect) {
  9. var options = (effect && effect.options) || NO_OPTIONS;
  10. if (env_1.env.isNode && !options.ssr) {
  11. return [null, null];
  12. }
  13. // eslint-disable-next-line react-hooks/rules-of-hooks
  14. return useRealSidecar(importer, effect);
  15. }
  16. exports.useSidecar = useSidecar;
  17. function useRealSidecar(importer, effect) {
  18. var options = (effect && effect.options) || NO_OPTIONS;
  19. var couldUseCache = env_1.env.forceCache || (env_1.env.isNode && !!options.ssr) || !options.async;
  20. var _a = (0, react_1.useState)(couldUseCache ? function () { return cache.get(importer); } : undefined), Car = _a[0], setCar = _a[1];
  21. var _b = (0, react_1.useState)(null), error = _b[0], setError = _b[1];
  22. (0, react_1.useEffect)(function () {
  23. if (!Car) {
  24. importer().then(function (car) {
  25. var resolved = effect ? effect.read() : car.default || car;
  26. if (!resolved) {
  27. console.error('Sidecar error: with importer', importer);
  28. var error_1;
  29. if (effect) {
  30. console.error('Sidecar error: with medium', effect);
  31. error_1 = new Error('Sidecar medium was not found');
  32. }
  33. else {
  34. error_1 = new Error('Sidecar was not found in exports');
  35. }
  36. setError(function () { return error_1; });
  37. throw error_1;
  38. }
  39. cache.set(importer, resolved);
  40. setCar(function () { return resolved; });
  41. }, function (e) { return setError(function () { return e; }); });
  42. }
  43. }, []);
  44. return [Car, error];
  45. }