Next.js Tutorial - Part 2 | Data Fetching with getInitialProps

https://www.youtube.com/watch?v=7J4iL1HDshQ&list=PLYSZyzpwBEWSQsrukurP09ksi49H9Yj40

Cách 1: Dùng với cách thông thường giống với ReactJs :(

C:\Users\Administrator\Desktop\abc\pages\list.js

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
export default function List({ownersList}) {
  const [owners, setOwners] = useState([]);
  useEffect(() => {
    async function loadData() {
      const response = await fetch('http://localhost:3000/vehicles');
      const ownersList = await response.json();
      setOwners(ownersList);
    }
    loadData();
  }, []);
  return (
    <div>
      {owners.map((e, index) => (
        <div key={index}>
          <Link as={`/${e.vehicle}/${e.ownerName}`} href="/[vehicle]/[person]">
            <a>
              Navigate to {e.ownerName}'s {e.vehicle}
            </a>
          </Link>
        </div>
      ))}
    </div>
  );
}

C:\Users\Administrator\Desktop\abc\pages[vehicle][person].js

import { useRouter } from 'next/router';
export default function Person() {
  const router = useRouter();
  console.log(router.query);
  return <h2>{router.query.person}'s {router.query.vehicle}</h2>
}

C:\Users\Administrator\Desktop\abc\db.json

{
    "vehicles": [
      {
        "vehicle": "Car",
        "ownerName": "Bruno Antunes",
        "details": "some detail about Bruno's Car"
      },
      {
        "vehicle": "Bike",
        "ownerName": "Bruno Antunes",
        "details": "some detail about Bruno's Bike"
      },
      {
        "vehicle": "Bike",
        "ownerName": "John Doe",
        "details": "some detail bile"
      },
      {
        "vehicle": "Airplane",
        "ownerName": "Bill Gates",
        "details": "some detail Bill Gates"
      } ,
      {
        "vehicle": "SpaceX",
        "ownerName": "Elon Musk",
        "details": "some detail Elon"
      }      
    ]
  }

C:\Users\Administrator\Desktop\abc\package.json

{
  "name": "abc",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "json": "json-server --watch db.json",
    "dev": "next dev -p 5000",
    "build": "next build && next export",
    "start": "next start"
  },
  "dependencies": {
    "isomorphic-unfetch": "^3.1.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }
}

Cách 2: Dùng với cách của Next.js là sử dụng getInitialProps

C:\Users\Administrator\Desktop\abc\pages\list.js

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
export default function List({ownersList}) {
  // const [owners, setOwners] = useState([]);
  // useEffect(() => {
  //   async function loadData() {
  //     const response = await fetch('http://localhost:4001/vehicles');
  //     const ownersList = await response.json();
  //     setOwners(ownersList);
  //   }

  //   loadData();
  // }, []);
  
  return (
    <div>
      {ownersList.map((e, index) => (
        <div key={index}>
          <Link as={`/${e.vehicle}/${e.ownerName}`} href="/[vehicle]/[person]">
            <a>
              Navigate to {e.ownerName}'s {e.vehicle}
            </a>
          </Link>
        </div>
      ))}
    </div>
  );
}
List.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/vehicles');
  const ownersList = await response.json();
  return {ownersList}
}

Last updated

Was this helpful?