useEffectでレースコンディションを防ぐ

#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;

}}


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS