読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
読み込みの状態を、ユニオン型の state で表します。
type LoadState =
| { status: "loading" }
| { status: "success"; products: Product[] }
| { status: "error"; message: string };
export const ProductCatalog = () => {
const [state, setState] = useState<LoadState>({ status: "loading" });
useEffect(() => {
let ignore = false;
const load = async () => {
try {
const response = await fetch("/products.json");
if (!response.ok) {
throw new Error(`読み込みに失敗しました(${response.status})`);
}
const products = (await response.json()) as Product[];
if (!ignore) {
setState({ status: "success", products });
}
} catch {
if (!ignore) {
setState({ status: "error", message: "商品を読み込めませんでした" });
}
}
};
load();
return () => {
ignore = true;
};
}, []);
if (state.status === "loading") return <p>商品を読み込んでいます…</p>;
if (state.status === "error") return <p>{state.message}</p>;
return <ProductList products={state.products} />;
};
| 部分 | すること |
|---|---|
LoadState | 読み込み中・成功・失敗のどれかを表す |
let ignore = false | この読み込みの結果を使ってよいか |
後片付けで ignore = true | 部品が消えたあとに届いた結果を捨てる |
useEffect に渡す関数には、async を付けられません。中で async の関数を作って呼びます。
11 / 17