All files / src/suspend index.tsx

100% Statements 13/13
100% Branches 3/3
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      2x   12x 12x   8x 8x     4x 4x       12x 23x   9x   13x   1x        
/*
 * Suspends a provided promise for `React.Suspense`.
 *
 * Creating suspense!
 *
 * @returns () => T
 *   Used to get the state of a suspended promise.
 *   It's important to recognize that this is needed so that `React.ErrorBoundary` works correctly.
 *   Only because this function will throw the promise error if there was one.
 *   Otherwise react won't know about the error.
 */
export const suspend = <T,>(promise: Promise<T>): (() => T) => {
  let result: T;
  let status = 'pending';
  const suspender = promise.then(
    response => {
      status = 'success';
      result = response;
    },
    error => {
      status = 'error';
      result = error;
    },
  );
 
  return (): T => {
    switch (status) {
      case 'pending':
        throw suspender;
      case 'error':
        throw result;
      default:
        return result;
    }
  };
};