- Import the required modules in your Next.js page:
import { useEffect, useState } from 'react';
- Create a function to fetch data using the
fetch
API:
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
};
- Define a functional component and use the
useState
hook to manage the state of the fetched data:
const MyPage = () => {
const [data, setData] = useState(null);
useEffect(() => {
const getData = async () => {
const result = await fetchData();
setData(result);
};
getData();
}, []); // The empty dependency array ensures the effect runs only once on mount
return (
<div>
{/ Render your component based on the fetched data /}
{data && (
<div>
<h1>Data from the API:</h1>
{/ Render data properties as needed /}
<p>{data.property1}</p>
<p>{data.property2}</p>
</div>
)}
</div>
);
};
export default MyPage;