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?

react-router-dom(v7)の使い方

Last updated at Posted at 2024-12-24

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>
    </>
  );
};

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?