Lesson 11-Next.js Page Routing-Data Fetching

Server-Side Rendering (SSR)

Use the getServerSideProps function to fetch data and render pages on the server.

// pages/post/[id].js
export default function PostPage({ post }) {
  return (
    <div>
      <h1>Post ID: {post.id}</h1>
      <p>Title: {post.title}</p>
      <p>Content: {post.content}</p>
    </div>
  );
}

export async function getServerSideProps(context) {
  const { params } = context;
  const id = params.id;

  // Simulate fetching data from a database
  const response = await fetch(`https://example.com/api/posts/${id}`);
  const post = await response.json();

  return {
    props: {
      post,
    },
  };
}

Static Site Generation (SSG)

Use the getStaticProps and getStaticPaths functions to fetch data and generate static pages at build time.

// pages/post/[id].js
export default function PostPage({ post }) {
  return (
    <div>
      <h1>Post ID: {post.id}</h1>
      <p>Title: {post.title}</p>
      <p>Content: {post.content}</p>
    </div>
  );
}

export async function getStaticProps(context) {
  const { params } = context;
  const id = params.id;

  // Simulate fetching data from a database
  const response = await fetch(`https://example.com/api/posts/${id}`);
  const post = await response.json();

  return {
    props: {
      post,
    },
  };
}

export async function getStaticPaths() {
  // Simulate fetching all post IDs from a database
  const response = await fetch('https://example.com/api/posts');
  const posts = await response.json();

  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },
  }));

  return {
    paths,
    fallback: false, // Can be set to 'blocking' or 'unstable_blocking' for dynamic routes
  };
}

Client-Side Rendering (CSR)

Use React Hooks like useEffect and useState to fetch data on the client side.

// pages/chat/index.js
import { useState, useEffect } from 'react';

export default function ChatPage() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const fetchMessages = async () => {
      const response = await fetch('/api/messages');
      const data = await response.json();
      setMessages(data);
    };

    fetchMessages();
  }, []);

  return (
    <div>
      <h1>Chat Room</h1>
      <ul>
        {messages.map((message) => (
          <li key={message.id}>{message.text}</li>
        ))}
      </ul>
    </div>
  );
}

Incremental Static Regeneration (ISR)

Use the revalidate option to specify when a page should be regenerated.

// pages/post/[id].js
export default function PostPage({ post }) {
  return (
    <div>
      <h1>Post ID: {post.id}</h1>
      <p>Title: {post.title}</p>
      <p>Content: {post.content}</p>
    </div>
  );
}

export async function getStaticProps(context) {
  const { params } = context;
  const id = params.id;

  // Simulate fetching data from a database
  const response = await fetch(`https://example.com/api/posts/${id}`);
  const post = await response.json();

  return {
    props: {
      post,
    },
    revalidate: 60, // Regenerate the page every 60 seconds
  };
}

export async function getStaticPaths() {
  // Simulate fetching all post IDs from a database
  const response = await fetch('https://example.com/api/posts');
  const posts = await response.json();

  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },
  }));

  return {
    paths,
    fallback: false, // Can be set to 'blocking' or 'unstable_blocking' for dynamic routes
  };
}
Share your love