🔰

【Next.js入門】 getStaticProps()で外部APIをFetchする【TypeScript】

2023/07/17に公開

はじめに

フロントエンドを勉強中の初心者です。
Next.jsでサーバーサイド、クライアントサイドそれぞれでAPIをFetchしました。
#Next.js13
#Typescript

外部API

今回はテスト用に{JSON} Placeholderのデータを使います。
https://jsonplaceholder.typicode.com/

getStaticProps()で外部APIをFetchする

create appしたらトップページにgetStaticProps()でデータを取得してみる。
index.tsx

import { GetStaticProps, NextPage } from "next";

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users`)
  const data = await res.json()
  return {
      props: { auth0Data: data },
  }
}
interface Auth0DataProps {
  id: number,
  name: string,
  username: string,
}

type Props = {
  auth0Data: Auth0DataProps[]
}

const Auth: NextPage<Props> = ({ auth0Data }) => {

    return <>
    <Head>
        <title>Create Next App</title>
      </Head>
      <main className={styles.main}>
        <h1>* 名前一覧 *</h1>
        <ul>
          {auth0Data.map(data=> 
          <li key={data.id}>
            {data.name}
          </li>)}
        </ul>

表示された一覧はこんな感じ。

せっかくなので外部APIをFetchする部分を共通部品にしてみる。
src > components > lib > auth.tsxを作成

export async function getAuth() {
    const res = await fetch(`https://jsonplaceholder.typicode.com/users`)
    const data = await res.json()
    return data
}

index.tsxのgetStaticPropsを書き換える。

import { getAuth } from '@/components/lib/auth'

export const getStaticProps: GetStaticProps = async () => {
  const auth0Data = await getAuth();
  return {
      props: { auth0Data },
  }
}

共通化して表示することができた!

あとがき

次はgetServerSideProps()を使った場合や、
useEffectを使ったクライアントサイドからFetchする場合を書きたい!

Discussion