v7からdeferが非推奨
v7より前
import { Await, useLoaderData, LoaderFunction,defer } from "react-router-dom";
export const flowLoader: LoaderFunction = async ({ params: { flowId } }) => {
if (!flowId) throw new Error("No id provided");
return defer({
comment: fetchComment(),
article: await fetchArticle(),
});
};
deferの記述が不要になった
v7
import { Await, useLoaderData, LoaderFunction } from "react-router-dom";
export const flowLoader: LoaderFunction = async ({ params: { flowId } }) => {
if (!flowId) throw new Error("No id provided");
return {
comment: fetchComment(),
article: await fetchArticle(),
};
};
const fetchArticle = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: "article1" });
}, 1000);
});
};
const fetchComment = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ title: "test comment" });
}, 3000);
});
};
type Article = {
name: string;
};
type Comment = {
title: string;
};
type LoaderData = {
comment: Promise<Comment>;
article: Article;
};
export const flowLoader: LoaderFunction = async ({ params: { flowId } }) => {
if (!flowId) throw new Error("No id provided");
return {
comment: fetchComment(),
article: await fetchArticle(),
};
};
const FlowLayout = () => {
const { article, comment } = useLoaderData() as LoaderData;
return (
<>
<div className="text-red-800">{article.name}</div>
<Suspense fallback={<div className="text-red-400">Loading Comments...</div>}>
<Await resolve={comment} errorElement={<div className="bg-black text-white">Failed to load comments.</div>}>
{(commentData) => <div className="text-blue-500">{commentData.title}</div>}
</Await>
</Suspense>
</>
);
};