Updating Contacts with FormData

김동현·2023년 3월 16일
0

React Router

목록 보기
12/31

Form UI는 앞에서 만들었다.

이제 데이터를 업데이트하기 위해 route에 action을 달아보자.

<Form> 이 action에 POST 요청을 하면 데이터는 자동으로 재검증 되므로 useLoaderData가 재실행된다

Add an action to the edit module

// 📄src/routes/edit.jsx

import {
  Form,
  useLoaderData,
  redirect,
} from "react-router-dom";
import { updateContact } from "../contacts";

export async function action({ request, params }) {
  const formData = await request.formData();
  const updates = Object.fromEntries(formData);
  await updateContact(params.contactId, updates);
  return redirect(`/contacts/${params.contactId}`);
}

/* existing code */

Wire the action up to the route

// 📄src/main.jsx

/* existing code */
import EditContact, {
  action as editAction,
} from "./routes/edit";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    errorElement: <ErrorPage />,
    loader: rootLoader,
    action: rootAction,
    children: [
      {
        path: "contacts/:contactId",
        element: <Contact />,
        loader: contactLoader,
      },
      {
        path: "contacts/:contactId/edit",
        element: <EditContact />,
        loader: contactLoader,
        action: editAction,
      },
    ],
  },
]);

/* existing code */

폼을 기입해 "save"을 클릭하면 다음과 같은 화면이 나온다.

출처 : 리액트 라우터 공식 홈페이지➡️

profile
프론트에_가까운_풀스택_개발자

0개의 댓글