All files / api/trimet-client/src useStopCatalog.ts

100% Statements 20/20
83.33% Branches 5/6
100% Functions 8/8
100% Lines 14/14

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                              400x 400x 400x   400x 64x 64x   64x 64x 57x 55x               7x     64x 64x     400x    
import { useCallback, useEffect, useState } from "react";
import type { StopCatalog } from "./stopCatalog";
 
export type StopCatalogRequest<C extends StopCatalog> = (forceRefresh: boolean) => Promise<C>;
 
export interface StopCatalogState<C extends StopCatalog> {
  catalog?: C;
  error: boolean;
  fetchedAt?: Date;
  loading: boolean;
}
 
export function useStopCatalog<C extends StopCatalog & { receivedAt?: string }>(
  request: StopCatalogRequest<C>,
) {
  const [state, setState] = useState<StopCatalogState<C>>({ error: false, loading: true });
  const [revision, setRevision] = useState(0);
  const refresh = useCallback(() => setRevision(value => value + 1), []);
 
  useEffect(() => {
    let active = true;
    setState(previous => ({ ...previous, error: false, loading: true }));
    async function load() {
      try {
        const catalog = await request(revision > 0);
        if (active) {
          setState({
            catalog,
            error: false,
            fetchedAt: catalog.receivedAt ? new Date(catalog.receivedAt) : new Date(),
            loading: false,
          });
        }
      } catch {
        Eif (active) setState(previous => ({ ...previous, error: true, loading: false }));
      }
    }
    void load();
    return () => { active = false; };
  }, [request, revision]);
 
  return { ...state, refresh };
}