10LOC

#data-fetching

Reactadvanced

Suspense data fetching with a thrown promise cache

type Resource<T> = { read: () => T };

const cache = new Map<string, Resource<unknown>>();

export const getResource = <T,>(key: string, fetchData: () => Promise<T>): Resource<T> => {

Build the tiny promise cache that makes Suspense-based data fetching work: throw while pending, cache the result, return it once resolved.