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",
},
});
富山在住のプログラマー。
フルリモートで働いています。
Categories
AWS
Cloudflare
Docker
Github
go
html
JavaScript
microCMS
MySQL
Monthly Archives
2025/01 (1)
2024/12 (4)
2024/11 (3)
2024/10 (1)
2024/09 (3)
2024/08 (7)
2024/07 (7)
2024/06 (4)
2024/05 (5)
2024/04 (6)