Skip to content

Instantly share code, notes, and snippets.

@melpon

melpon/index.tsx

Last active Sep 10, 2019
Embed
What would you like to do?
import React from "react";
import ReactDOM from "react-dom";
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 [person, setPerson] = React.useState<Person | null>(null);
const onError = (error: string): void => {
// 何かのエラー処理
console.error(error);
};
const headers = { "Content-Type": "application/json" };
// 取得
const [personResp, , doGetPerson] = useFetchJSON<Person>(
"/api/person",
{ method: "GET", headers },
resolvePerson,
onError
);
// 更新
const [, personPostId, doPostPerson] = useFetchJSON<{}>(
"/api/person",
{ method: "POST", headers },
(): {} => ({}),
onError
);
// 初回と POST が完了した時に取得を実行する
React.useEffect((): void => {
doGetPerson(null, {});
}, [personPostId]);
// 取得が完了したら状態を更新する
React.useEffect((): void => {
if (personResp === null) return;
setPerson(personResp);
}, [personResp]);
// age++ する
const onClickUpdate = React.useCallback((): void => {
if (person === null) return;
doPostPerson(null, {
body: JSON.stringify({ name: person.name, age: person.age + 1 })
});
}, [person]);
if (person === null) {
return null;
}
return (
<div>
<p>name:{person.name}</p>
<p>age:{person.age}</p>
<button onClick={onClickUpdate}>Update</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root") as HTMLElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment