import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect*1
.catch(error => console.error('There was a problem with your fetch operation:', error));
}, []); // 空の依存配列を渡すことで、コンポーネントのマウント時にのみ実行
return (
<div>
<h1>Data from API</h1>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
export default App;
*1:) => {
fetch('https://api.example.com/data', {
method: 'GET', // HTTPメソッド
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.ok) {
return response.json(); // JSON形式のレスポンスをパース
}
throw new Error('Network response was not ok.');
})
.then(data => setData(data