Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
97 lines
2.4 KiB
TypeScript
97 lines
2.4 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
|
|
export type ResourceStatus = "loading" | "done" | "error";
|
|
|
|
export interface ResourceState<T> {
|
|
status: ResourceStatus;
|
|
data?: T;
|
|
error?: unknown;
|
|
}
|
|
|
|
const cache = new Map<string, unknown>();
|
|
const inFlight = new Map<string, Promise<unknown>>();
|
|
|
|
function cachedHit<T>(key: string | null): T | undefined {
|
|
if (key != null && cache.has(key)) return cache.get(key) as T;
|
|
return undefined;
|
|
}
|
|
|
|
function dedupedFetch<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
|
|
if (cache.has(key)) return Promise.resolve(cache.get(key) as T);
|
|
|
|
const running = inFlight.get(key) as Promise<T> | undefined;
|
|
if (running) return running;
|
|
|
|
const promise = fetcher()
|
|
.then((data) => {
|
|
cache.set(key, data);
|
|
return data;
|
|
})
|
|
.finally(() => {
|
|
inFlight.delete(key);
|
|
});
|
|
|
|
inFlight.set(key, promise);
|
|
return promise;
|
|
}
|
|
|
|
/**
|
|
* Loads a resource once per key, sharing the cache and in-flight requests
|
|
* across all mounts. Reports the fetched (or cached) value through `onData`
|
|
* so owners can hoist the result into their own state.
|
|
*/
|
|
export function useResource<T>(
|
|
key: string | null,
|
|
fetcher: (() => Promise<T>) | null,
|
|
onData?: (data: T) => void
|
|
): ResourceState<T> {
|
|
const fetcherRef = useRef(fetcher);
|
|
const onDataRef = useRef(onData);
|
|
useEffect(() => {
|
|
fetcherRef.current = fetcher;
|
|
onDataRef.current = onData;
|
|
});
|
|
|
|
const [state, setState] = useState<ResourceState<T>>(() => {
|
|
const hit = cachedHit<T>(key);
|
|
return hit !== undefined ? { status: "done", data: hit } : { status: "loading" };
|
|
});
|
|
|
|
const [prevKey, setPrevKey] = useState<string | null>(key);
|
|
if (key !== prevKey) {
|
|
setPrevKey(key);
|
|
const hit = cachedHit<T>(key);
|
|
setState(hit !== undefined ? { status: "done", data: hit } : { status: "loading" });
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!key || !fetcherRef.current) return;
|
|
|
|
if (cache.has(key)) {
|
|
onDataRef.current?.(cache.get(key) as T);
|
|
return;
|
|
}
|
|
|
|
let cancelled = false;
|
|
const run = fetcherRef.current;
|
|
|
|
dedupedFetch(key, run)
|
|
.then((data) => {
|
|
if (cancelled) return;
|
|
setState({ status: "done", data });
|
|
onDataRef.current?.(data);
|
|
})
|
|
.catch((err) => {
|
|
if (cancelled) return;
|
|
setState({ status: "error", error: err });
|
|
});
|
|
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [key]);
|
|
|
|
return state;
|
|
} |