Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@melpon
Last active September 10, 2019 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melpon/d77aea0e89f4c0a0f6a4cc10b976b080 to your computer and use it in GitHub Desktop.
Save melpon/d77aea0e89f4c0a0f6a4cc10b976b080 to your computer and use it in GitHub Desktop.
import { useFetchJSON, AnyJson, JsonMap } from "./fetch";
// レスポンスの型を定義
interface Person {
name: string;
age: number;
}
// 戻り値をレスポンスの型に変換
function resolvePerson(json: AnyJson): Person {
const map = json as JsonMap;
return {
name: map.name as string,
age: map.age as number
};
}
const App: React.FC<{}> = (): React.ReactElement | null => {
// 何かエラーが起きた時の処理
const onError = (error: string): void => {
console.error(error);
};
const headers = { "Content-Type": "application/json" };
// 取得
const [personResp, personFetchId, doGetPerson] = useFetchJSON<Person>(
"/api/person",
{ method: "GET", headers },
resolvePerson,
onError
);
// 初回だけ呼び出す
React.useEffect((): void => {
doGetPerson(null, {});
}, []);
// 取得前なら personResp === null に、
// 無事取得できてれば personResp !== null になってる
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment