Skip to content

Instantly share code, notes, and snippets.

@melpon
Last active September 10, 2019 16:25
Show Gist options
  • Save melpon/4d71e967d791ea12c04c4220edce7c90 to your computer and use it in GitHub Desktop.
Save melpon/4d71e967d791ea12c04c4220edce7c90 to your computer and use it in GitHub Desktop.
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