All files / src/hooks useResource.ts

94.02% Statements 63/67
85.71% Branches 18/21
100% Functions 2/2
94.02% Lines 63/67

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 861x 1x                   1x 346x 346x 346x 346x 346x 346x 346x 346x   346x 346x 346x   346x 6x 346x   346x 154x 154x   154x 157x 157x 157x 157x 1x 1x 147x 147x 147x 157x 8x     8x 8x   8x 8x   8x 157x 156x 155x 155x 156x 157x   154x   154x 8x 8x 8x 8x 8x   146x 3x 3x 3x 146x   146x 146x 146x 146x 146x 346x   346x 346x  
import { useCallback, useEffect, useRef, useState } from "react";
import { ApiError } from "../api/client";
 
export interface ResourceState<T> {
  data: T | null;
  error: string | null;
  loading: boolean;
  reload: () => void;
  updatedAt: Date | null;
}
 
export function useResource<T>(loader: () => Promise<T>, deps: unknown[], intervalMs = 0): ResourceState<T> {
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
  const [nonce, setNonce] = useState(0);
  const alive = useRef(true);
  const depsKey = JSON.stringify(deps);
  const loaderRef = useRef(loader);
 
  useEffect(() => {
    loaderRef.current = loader;
  });
 
  const reload = useCallback(() => {
    setNonce((value) => value + 1);
  }, []);
 
  useEffect(() => {
    alive.current = true;
    let cancelled = false;
 
    async function run() {
      setLoading(true);
      try {
        const result = await loaderRef.current();
        if (cancelled) {
          return;
        }
        setData(result);
        setError(null);
        setUpdatedAt(new Date());
      } catch (caught) {
        if (cancelled) {
          return;
        }
        const message =
          caught instanceof ApiError
            ? caught.message
            : caught instanceof Error
              ? caught.message
              : String(caught);
        setError(message);
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }
 
    void run();
 
    if (intervalMs <= 0) {
      return () => {
        cancelled = true;
        alive.current = false;
      };
    }
 
    const timer = setInterval(() => {
      if (alive.current) {
        void run();
      }
    }, intervalMs);
 
    return () => {
      cancelled = true;
      alive.current = false;
      clearInterval(timer);
    };
  }, [depsKey, intervalMs, nonce]);
 
  return { data, error, loading, reload, updatedAt };
}