일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- 클로저
- 타입스크립트
- createbrowserrouter
- revalidatepath
- client components
- render phase
- image component
- supabase realtime
- 프로그래머스
- unstable_nostore
- interceptor routes
- server components
- CSS
- dynamic pages
- 리액트
- sever action
- js
- static pages
- revalidatetag
- 3진법 뒤집기
- sever components
- @tailwind components
- 자바스크립트
- @tailwind base
- commit phase
- iron-session
- SSR
- RECOIL
- @tailwind utility
- @tailwind
- Today
- Total
개발하는 너구리
createBrowserRouter, loader, action 본문
React Router v6에서는 createBrowserRouter 함수를 사용하여 클라이언트 측 라우터를 생성할 수 있습니다. 이 함수는 주로 라우트 설정과 함께 데이터를 로드하거나 폼 제출을 처리하는 loader와 action을 정의하는 데 사용됩니다. 이들 함수는 라우트가 활성화될 때 데이터를 비동기적으로 로드하거나 폼 제출을 처리하는 데 매우 유용합니다.
createBrowserRouter 기본 구조
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";
import SomeComponent from "./SomeComponent";
import SomeOtherComponent from "./SomeOtherComponent";
import { loader as someLoader, action as someAction } from "./someComponentLoaderAction";
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{
path: "some-path",
element: <SomeComponent />,
loader: someLoader,
action: someAction,
},
{
path: "some-other-path",
element: <SomeOtherComponent />,
},
],
},
]);
function Root() {
return <RouterProvider router={router} />;
}
export default Root;
loader 함수
loader 함수는 라우트가 매칭될 때 데이터를 로드하는 비동기 함수입니다. 이 함수는 주로 컴포넌트가 렌더링되기 전에 데이터를 가져오는 데 사용됩니다. loader 함수는 Request 객체와 params를 인자로 받아 데이터를 반환해야 합니다. 반환된 데이터는 해당 라우트의 컴포넌트에서 useLoaderData 훅을 통해 접근할 수 있습니다.
예시:
import { LoaderFunction } from "react-router-dom";
export const loader: LoaderFunction = async ({ request, params }) => {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Failed to load data');
}
const data = await response.json();
return data;
};
action 함수
action 함수는 폼 제출을 처리하는 비동기 함수입니다. 이 함수는 주로 POST 요청을 처리하거나, 데이터베이스에 데이터를 저장하는 등의 작업을 수행합니다. action 함수는 Request 객체와 params를 인자로 받아야 하며, 필요한 경우 리디렉션이나 JSON 응답을 반환할 수 있습니다.
예시:
import { ActionFunction, redirect, json } from "react-router-dom";
export const action: ActionFunction = async ({ request, params }) => {
const formData = await request.formData();
const data = Object.fromEntries(formData);
const response = await fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
return json({ message: 'Failed to submit data' }, { status: 500 });
}
return redirect('/success');
};
예제: createBrowserRouter에서 loader와 action 사용
import { createBrowserRouter, RouterProvider, useLoaderData, Form } from "react-router-dom";
// SomeComponent.js
export const loader = async () => {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Failed to load data');
}
return response.json();
};
export const action = async ({ request }) => {
const formData = await request.formData();
const data = Object.fromEntries(formData);
const response = await fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
return json({ message: 'Failed to submit data' }, { status: 500 });
}
return redirect('/success');
};
const SomeComponent = () => {
const data = useLoaderData();
return (
<div>
<h1>Data Loaded</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
<Form method="post">
<input name="example" type="text" />
<button type="submit">Submit</button>
</Form>
</div>
);
};
// Router configuration
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{
path: "some-path",
element: <SomeComponent />,
loader: someLoader,
action: someAction,
},
{
path: "some-other-path",
element: <SomeOtherComponent />,
},
],
},
]);
function Root() {
return <RouterProvider router={router} />;
}
export default Root;
요약
loader 함수: 비동기 함수로, 라우트가 활성화될 때 데이터를 로드합니다. 데이터를 반환해야 하며, 반환된 데이터는 해당 라우트의 컴포넌트에서 useLoaderData 훅을 통해 접근할 수 있습니다.
action 함수: 비동기 함수로, 폼 제출을 처리합니다. 데이터를 서버로 전송하거나 다른 비동기 작업을 수행할 수 있으며, 리디렉션이나 JSON 응답을 반환할 수 있습니다.
createBrowserRouter: 이 함수는 클라이언트 측 라우터를 생성하며, 각 라우트에 대해 loader와 action을 설정할 수 있습니다.
이를 통해 React Router를 사용하여 복잡한 데이터 로드 및 폼 제출 작업을 간편하게 처리할 수 있습니다.
'TIL' 카테고리의 다른 글
Suspense components (0) | 2024.06.14 |
---|---|
SSR, React Server Components(RSC), Client Components (0) | 2024.06.12 |
Render Phase, Commit Phase (0) | 2024.06.06 |
Vitual DOM, React Fiber (0) | 2024.06.04 |
rendering (0) | 2024.05.31 |