Next.js Tutorial - Part 9 - Data Fetching with getServerSideProps 1

1. Hiển thị trang chủ

C:\Users\Administrator\Desktop\nextjs\pages\index.tsx

import { GetServerSideProps } from 'next';
import Link from 'next/link';
import { Microphone } from '../model/Microphone';
import  openDB  from '../openDB';
export interface IndexProps {
  microphones: Microphone[];
}
export default function Index({ microphones }: IndexProps) {
  return (
    <div>
      <Link href="/people">
        <a>People</a>
      </Link>
      <pre>{JSON.stringify(microphones, null, 4)}</pre>;
    </div>
  );
}
export const getServerSideProps: GetServerSideProps<IndexProps> = async (ctx) => {
  const db = await openDB();
  const microphones = await db.all<Microphone[]>('select * from microphone');
  return { props: { microphones } };
};

2. Hiển thị page people

import { GetServerSideProps } from 'next';
import Link from 'next/link';
export interface PeopleProps {
  names: string[];
}
export default function People({ names }: PeopleProps) {
  return (
    <div>
      <Link href="/">
        <a>Index</a>
      </Link>
      {
        names.map((name) => {
          return <h2 key={name}>{name}</h2>;
        })
      }
    </div>
  );
}
export const getServerSideProps: GetServerSideProps<PeopleProps> = async (ctx) => {
  return { 
    props: { 
      names: ['john', 'doe', 'michael', 'bruno'] 
    } 
  };
};

Last updated

Was this helpful?