Dynamic API Route Data Fetching
Illustrate fetching data from dynamic API routes based on user input or URL parameters using getServerSideProps or getStaticProps.
import { useRouter } from 'next/router';
export async function getServerSideProps(context) {
const { params, query } = context;
const { id } = params; // Get dynamic part of the URL
const res = await fetch(`https://api.example.com/data/${id}`);
const data = await res.json();
return {
props: { data }, // Will be passed to the page component as props
};
}
export default function Page({ data }) {
// Render data here
return <div>{JSON.stringify(data)}</div>;
}
This code snippet defines a Next.js page with getServerSideProps. It illustrates how to fetch data on the server side based on a dynamic route parameter (e.g., id). The fetched data is then passed as props to the page component, which renders it.