Introduction to Data Fetching
Fetching data is a common task in web development. In Next.js, you can fetch data at build time and pre-render pages using the getStaticProps
function. This allows you to create static, SEO-friendly pages with dynamic data. In this tutorial, we'll explore how to fetch data with getStaticProps
in Next.js.
Using getStaticProps
1. Create a new page in the "pages" directory, for example, data-fetching.js
:
<pre>
// pages/data-fetching.js
import React from 'react';
function DataFetchingPage({ data }) {
return (
<div>
<h2>Data Fetching</h2>
<p>{data}</p>
</div>
);
}
export async function getStaticProps() {
// Fetch data during build time
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return {
props: {
data,
},
};
}
export default DataFetchingPage;
</pre>
In this example, the getStaticProps
function is used to fetch data during the build process and pass it as a prop to the component. The page is pre-rendered with dynamic data.
2. Build your Next.js application using:
<pre>
npm run build
</pre>
3. Start your Next.js application using:
<pre>
npm run start
</pre>
4. Access the data-fetching page by visiting /data-fetching
in your application. The page is pre-rendered with the fetched data.