Last active
February 21, 2025 15:13
-
-
Save mach3/fc56ebba725ff0af2db0a2eb8bb03b5c to your computer and use it in GitHub Desktop.
Suspense用にデータフェッチするhook
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 { useState } from "react"; | |
export class Loadable<T> { | |
private promise: Promise<T>; | |
private value?: T; | |
private error?: unknown; | |
private status: "pending" | "resolved" | "rejected" = "pending"; | |
constructor(promise: Promise<T>) { | |
this.promise = promise | |
.then((value) => { | |
this.status = "resolved"; | |
this.value = value; | |
return value; | |
}) | |
.catch((error) => { | |
this.status = "rejected"; | |
this.error = error; | |
throw error; | |
}); | |
} | |
load(): T { | |
if (this.status === "pending") { | |
throw this.promise; | |
} | |
if (this.status === "rejected") { | |
throw this.error; | |
} | |
return this.value as T; | |
} | |
} | |
export function useLoadable<T>( | |
promise: Promise<T>, | |
): [Loadable<T>, (promise: Promise<T>) => void] { | |
const [loadable, setLoadable] = useState(new Loadable(promise)); | |
const setLoadablePromise = (promise: Promise<T>) => { | |
setLoadable(new Loadable(promise)); | |
}; | |
return [loadable, setLoadablePromise]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment