Next.js Data Fetching
Next.js provides multiple data fetching methods, allowing you to fetch and display data at different rendering stages (e.g., server-side rendering, static generation, and client-side rendering).
Client-side Data Fetching
Sometimes you want to fetch data from the client after the page loads, rather than at build time or server-side. You can use React's useEffect hook to handle client-side data fetching.
Using useEffect and fetch
Use the useEffect hook and fetch API to fetch data in React components.
useEffect executes after the component mounts, where you can make API requests and update state.
app/posts/page.tsx File Code:
// app/posts/page.tsx
'use client';
import{ useEffect, useState } from 'react';
export default function PostsPage(){
const[posts, setPosts]= useState([]);
useEffect(()=>{
const fetchPosts = async ()=>{
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
setPosts(data);
};
fetchPosts();
},[]);
return(
<div>
<h1> Test</h1>
<ul>
{posts.map(post =>(
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
Visit http://localhost:3000/posts, the display structure is as follows:
useEffect executes after client-side rendering, suitable for client-side rendered data.
- Fetching data on the client is suitable for content that doesn't need server-side rendering.
- You can dynamically fetch data based on user interactions or time factors.
Use Cases:
- Dynamically loaded data, such as infinite scrolling or pagination.
- Data fetched after user operations, such as fetching data after clicking a button.
Server-side Data Fetching
Server-side data can be fetched using the following methods:
- fetch API
- ORM or database
Using fetch API
To use the fetch API to fetch data, you need to convert your component to an async function and use await to wait for the fetch call. Example as follows:
app/posts/page.tsx File Code:
// app/posts/page.tsx
export default async function Page(){
const data = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await data.json()
return(
<ul>
{posts.map((post)=>(
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
Using ORM or Database
You can also fetch data through ORM or database by simply converting your component to an async function and waiting for the database call:
app/posts/page.tsx File Code:
// app/posts/page.tsx
import{ db, posts } from '@/lib/db'
export default async function Page(){
const allPosts = await db.select().from(posts)
return(
<ul>
{allPosts.map((post)=>(
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
YouTip