Last active
December 6, 2022 08:57
-
-
Save Sheraff/3b3340b61dd512a77a6a07b0720294df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Suspense } from "react"; | |
type CacheItem<T> = { | |
keys: any[] | |
promise: Promise<T> | |
error?: unknown | |
response?: T | |
} | |
const cache: CacheItem<any>[] = [] | |
function findInCache<T>(callback: () => Promise<T>, keys: any[]) { | |
for (const item of cache) { | |
if (item.keys.every((key, i) => key === keys[i])) { | |
return item as CacheItem<T> | |
} | |
} | |
const item: CacheItem<T> = { | |
keys, | |
promise: callback(), | |
} | |
cache.push(item) | |
item.promise | |
.then((response) => { | |
item.response = response | |
}) | |
.catch((error) => { | |
item.error = error | |
}) | |
return item | |
} | |
function useSuspend<T>(callback: () => Promise<T>, deps: any[]): T { | |
const item = findInCache(callback, deps) | |
if (item.response) return item.response | |
if (item.error) throw item.error | |
throw item.promise | |
} | |
function Later() { | |
const data = useSuspend(() => new Promise(r => setTimeout(() => r("yooooo"), 3_000)), []) | |
return <p>{data}</p> | |
} | |
export default function Test() { | |
return ( | |
<div> | |
<p>hello</p> | |
<Suspense fallback={<p>Loading...</p>}> | |
<Later /> | |
</Suspense> | |
<p>good bye</p> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment