Last active
September 10, 2019 17:23
-
-
Save melpon/d77aea0e89f4c0a0f6a4cc10b976b080 to your computer and use it in GitHub Desktop.
This file contains 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 { 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