- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2022-02-07T15:57:10+09:00","default:ryuichi","ryuichi")
* useEffectでレースコンディションを防ぐ [#a103ca00]
#sh(javascript){{
import { useEffect, useState } from "react";
function App() {
const [id, setId] = useState(0);
const [name, setName] = useState("");
useEffect(() => {
void (async () => {
const response = await fetch(`https://swapi.dev/api/people/${id}/`);
const data = await response.json();
setName(data.name);
})();
}, [id]);
return (
<div className="App">
<button
onClick={() => {
const id = Math.round(Math.random() * 30);
setId(id);
}}
>
Fetch data
</button>
<p>ID: {id}</p>
<p>Name: {name}</p>
</div>
);
}
export default App;
}}