Waka blog.

Remix -> React Router移行後に発生したエラー解消

React Router移行後、 npm run dev で起動して画面を表示するとコンソールに以下のエラーが表示された。

Error: Expected a Response to be returned from resource route handler
    at invariant3 (/Users/wakaapps/develop/study/remix/waka.apps.blog/node_modules/react-router/dist/development/index.js:8682:11)
    at handleResourceRequest (/Users/wakaapps/develop/study/remix/waka.apps.blog/node_modules/react-router/dist/development/index.js:9418:5)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at requestHandler (/Users/wakaapps/develop/study/remix/waka.apps.blog/node_modules/react-router/dist/development/index.js:9204:18)
    at /Users/wakaapps/develop/study/remix/waka.apps.blog/node_modules/@react-router/dev/dist/vite/cloudflare.js:171:25

以下のようにコンポーネントを返さずAPIエンドポイントとして利用していたloaderで、生のデータを返却していたのが原因。

import { LoaderFunctionArgs } from "react-router";
import { client } from "~/libs/client.server";
import { Post } from "~/types/post";

export const LIMIT = 20;

export type BlogResponse = {
  posts: Post[];
  totalCount: number;
  nextOffset: number;
  hasNextPage: boolean;
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const offset = Number(url.searchParams.get("offset")) || 0;
  const categoryId = url.searchParams.get("categoryId") || "";

  const filters = categoryId && `categories[contains]${categoryId}`;

  const data = await client.getList<Post>({
    endpoint: "blog",
    queries: {
      offset: offset,
      limit: LIMIT,
      filters: filters,
    },
  });

  const res: BlogResponse = {
    posts: data.contents,
    totalCount: data.totalCount,
    nextOffset: data.offset + LIMIT,
    hasNextPage: data.offset <= data.totalCount,
  };

  // ↓※ここでデータをそのまま返していたのが原因
  return res;
};

v3_singleFetch モードを有効にした結果、loaderの戻り値を生データに変更していたのだがこれが有効なのはあくまでコンポーネントとセットのloaderだけだった模様。

以下のようにResponse型として返却することで解消した。

return new Response(JSON.stringify(res), {
    headers: {
      "Content-Type": "application/json",
    },
  });