0
0

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】備忘録:Error: Objects are not valid as a React child (found: [object Promise])〜でハマった時と解決策

Last updated at Posted at 2023-07-13

Next.jsでブログサイトを作成している際、getStaticPropsを実行したところ、以下のようなエラーが表示されました。

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

このエラーの解決に時間がかかったため、このエラーが起きた時の解決策をまとめました。



◆ エラーの意味

Nextjs エラー: オブジェクトは React の子として有効ではありません (見つかった: [オブジェクト Promise])。子のコレクションをレンダリングする場合は、代わりに配列を使用してください

Google翻訳ですが上記のような意味になります。

正直何のこと言っているのか意味がわかりません...。

取得した結果を見たけど取得結果も配列じゃないし。



◆ このエラーが出たときに疑うことは

どの現象でこのエラーが出るのか全パターンを行ったわけではないのですが、このエラーが出たときは、

基本的にソースの書き方がどこかで間違っている

ってことでいいのではないかと思います。

いわゆる初歩的な単純ミスです。



◆エラーの原因① ~不要なasync~

不要なasyncがあるとこのようなエラーが出るそうです。
自分の原因はこれではなかったのですが、同様のエラーが出ている方がQ&Aを出されていたため、参考に。



◆エラーの原因② ~export defaultの間違い~

自分の場合の原因はこれでした。
pages配下で表示するページコンポーネントをdefaultにするのではなく、getStaticPropsの方をexport defaultしていたことが間違いでした。

(getStaticPropsどうこうではなく、そもそもページが開けないソースになってました..。)

import { client } from "../../lib/api";
import { getPostBySlug } from "../../lib/api";

type props = {
  title: string;
  publish: string;
  content: string;
  eyecatch: any;
  categories: any;
};

export const TestPage = ({
  title,
  publish,
  content,
  eyecatch,
  categories,
}: props) => {
  return (
    <>
      <h1>{title}</h1>
      {content}
    </>
  );
};


export default async function getStaticProps() {
  const slug = "test";

  const post = await getPostBySlug(slug);

  return {
    props: {
      title: post.title,
      publish: post.publishDate,
      content: post.content,
      eyectch: post.eyecatch,
      categories: post.categories,
    },
  };
}

getStaticPropsをexportにし、ページコンポーネントをexport defaultに変えたら普通に解決しました。



エラーに惑わされて本質は全然違うことよくありますよね...。
これで全てが解決するかはわかりませんが、宜しければ参考にしてください!!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?