Skip to content

Instantly share code, notes, and snippets.

@developit
Last active October 20, 2025 19:07
Show Gist options
  • Save developit/7227a5b2499aae0ea27c36129e64259c to your computer and use it in GitHub Desktop.
Save developit/7227a5b2499aae0ea27c36129e64259c to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'preact/hooks';
const cache = new Map<string, any>();
const inflight = new Map<string, Promise<any>>();
export interface SWRResponse<T> {
data: T | undefined;
error: Error | null;
loading: boolean;
}
export function useSWR<T>(key: string | null, fetcher: (key: string) => Promise<T>): SWRResponse<T> {
const [data, setData] = useState<T | undefined>(cache.get(key ?? ''));
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(!cache.has(key ?? ''));
useEffect(() => {
if (!key) return;
(async () => {
if (inflight.has(key)) {
try {
const result = await inflight.get(key);
setData(result);
setError(null);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
return;
}
setLoading(true);
const promise = fetcher(key);
inflight.set(key, promise);
try {
const result = await promise;
cache.set(key, result);
setData(result);
setError(null);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
inflight.delete(key);
}
})();
}, [key]);
return { data, error, loading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment