1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js / React – URL を Fetchする例 (初心者) ( TypeError: ... is not a function )

Posted at

成功するコード例

pages/_app.tsx

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import React from "react";

export const doFetch = async () => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  console.log(json);
}

export default function App({ Component, pageProps }: AppProps) {
  doFetch();
  return <Component {...pageProps} />
}

async な function 内で fetch を実行しないとダメっぽい

ダメな例

  • 同期 function の中では実行できない
  • resから派生する関数 ( res.json() ) とかが使えない
  • fetch の返り値としては Promise が返って来るがそのままは使っても意味がない
  • function が async ではないので await もできない
export default function App({ Component, pageProps }: AppProps) {
  const res = fetch('https://api.github.com/repos/zeit/next.js')
  console.log(res.json())
  return <Component {...pageProps} />
}

エラー

Server Error
TypeError: res.json is not a function

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?