Skip to content

Instantly share code, notes, and snippets.

@mach3
Last active February 21, 2025 15:13
Show Gist options
  • Save mach3/fc56ebba725ff0af2db0a2eb8bb03b5c to your computer and use it in GitHub Desktop.
Save mach3/fc56ebba725ff0af2db0a2eb8bb03b5c to your computer and use it in GitHub Desktop.
Suspense用にデータフェッチするhook
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