import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(); // データを保存するための状態
const [loading, setLoading] = useState(true); // ローディング状態の管理
const [error, setError] = useState(null); // エラーの状態管理
useEffect(() => {
fetch('https://api.example.com/users') // ここにAPIのURLを入力
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
console.error('There was a problem with your fetch operation:', error);
setError(error.message);
setLoading(false);
});
}, ); // 空の依存配列を渡して、コンポーネントのマウント時にのみ実行されるようにする
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h1>Users</h1>
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default App;