Skip to content

Instantly share code, notes, and snippets.

@Sheraff
Last active December 6, 2022 08:57
Show Gist options
  • Save Sheraff/3b3340b61dd512a77a6a07b0720294df to your computer and use it in GitHub Desktop.
Save Sheraff/3b3340b61dd512a77a6a07b0720294df to your computer and use it in GitHub Desktop.
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