1
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?

react-router で複数 API からリソースをフェッチしたい

Posted at

はじめに

react-router 好き guppy0356 です。今日は loader のなかで複数 API からリソースをフェッチしたい場合の忘備録です。

どうするのか

Promise で良いとき

オブジェクトでラップして返して上げましょう。qiita.fetchItemsmicrocms.fetchContents は Promise を返します。

export async function loader() {
  return { qiitaItems: qiita.fetchItems(), microcmsItems: microcms.fetchContents() }
}

フェッチを完全に終えたいとき

Promise.all を使って処理が終わるまで待ちましょう。

export async function loader() {
  let [qiitaItems, microcmsItems] = await Promise.all([
    qiita.fetchItems(),
    microcms.fetchContents()
  ]);

  return { qiitaItems, microcmsItems }
}

ハマりそうなこと

フェッチを完全に終えたい、かつ loader を定義しない場合は、次のようなコンポーネントを作成することも可能です。サーバーコンポーネントなので問題ありませんね。

export default async function individuals() {
  let [qiitaItems, microcmsItems] = await Promise.all([
    qiita.fetchItems(),
    microcms.fetchContents()
  ]);

  const [value, setValue] = useState(0)

  return (
    <div className="w-full px-20 py-20">
      <p>{ qiitaItems.length }</p>
      <p>{ microcmsItems.length }</p>
      { value }
    </div>
  );
}

このとき useState を使って state 管理をしようとすると次のようなメッセージが出てきます。async/await はサーバーコンポーネントでしか使えません :rolling_eyes:

async/await is not yet supported in Client Components, only Server Components. 
This error is often caused by accidentally adding `'use client'` to
a module that was originally written for the server.
1
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
1
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?