useStoriesLoader.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import {useCallback, useEffect, useState} from 'react';
  2. import storiesContext from 'sentry/views/stories/storiesContext';
  3. import type {ResolvedStoryModule} from 'sentry/views/stories/types';
  4. interface Props {
  5. filename: string;
  6. }
  7. interface EmptyState {
  8. error: undefined;
  9. filename: undefined | string;
  10. resolved: undefined;
  11. }
  12. interface ResolvedState {
  13. error: undefined;
  14. filename: string;
  15. resolved: ResolvedStoryModule;
  16. }
  17. interface ErrorState {
  18. error: Error;
  19. filename: undefined | string;
  20. resolved: undefined;
  21. }
  22. type State = EmptyState | ResolvedState | ErrorState;
  23. export default function useStoriesLoader({filename}: Props) {
  24. const [mod, setMod] = useState<State>({
  25. error: undefined,
  26. filename,
  27. resolved: undefined,
  28. });
  29. const asyncImportStory = useCallback(async () => {
  30. if (!filename) {
  31. return;
  32. }
  33. try {
  34. setMod({
  35. error: undefined,
  36. filename,
  37. resolved: undefined,
  38. });
  39. const resolved = await storiesContext().importStory(filename);
  40. setMod({
  41. error: undefined,
  42. filename,
  43. resolved,
  44. });
  45. } catch (error) {
  46. setMod({
  47. error,
  48. filename,
  49. resolved: undefined,
  50. });
  51. }
  52. }, [filename]);
  53. useEffect(() => {
  54. asyncImportStory();
  55. }, [asyncImportStory]);
  56. return mod;
  57. }