useStoriesLoader.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. const resolved = await storiesContext().importStory(filename);
  35. setMod({
  36. error: undefined,
  37. filename,
  38. resolved,
  39. });
  40. } catch (error) {
  41. setMod({
  42. error,
  43. filename,
  44. resolved: undefined,
  45. });
  46. }
  47. }, [filename]);
  48. useEffect(() => {
  49. asyncImportStory();
  50. }, [asyncImportStory]);
  51. return mod;
  52. }