일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- createbrowserrouter
- interceptor routes
- supabase realtime
- @tailwind utility
- static pages
- client components
- unstable_nostore
- CSS
- revalidatetag
- 3진법 뒤집기
- revalidatepath
- SSR
- js
- sever components
- sever action
- commit phase
- RECOIL
- 클로저
- 프로그래머스
- dynamic pages
- iron-session
- 타입스크립트
- 리액트
- @tailwind base
- 자바스크립트
- server components
- @tailwind
- @tailwind components
- render phase
- image component
Archives
- Today
- Total
개발하는 너구리
useFormState, useFormStatus 본문
Next.js에서 useFormState와 useFormStatus 사용하기
1. useFormState
useFormState 훅은 Next.js에서 양식 데이터를 관리하고 유효성 검사를 수행하는 데 사용되는 Hook입니다.
기능:
- 양식 데이터를 저장하고 업데이트합니다.
- 양식 오류 메시지를 관리합니다.
- 양식 제출 처리를 수행합니다.
사용 방법:
const MyForm = () => {
const { state, handleChange, handleSubmit } = useFormState({
initialValues: {
name: '',
email: '',
},
});
const onSubmit = (event) => {
event.preventDefault();
handleSubmit(async (values) => {
// 서버로 양식 데이터 전송
const response = await fetch('/api/submit-form', {
method: 'POST',
body: JSON.stringify(values),
});
if (response.ok) {
// 성공 처리
console.log('양식 제출 완료!');
} else {
// 오류 처리
console.error('양식 제출 실패!');
}
});
};
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">이름:</label>
<input type="text" id="name" name="name" value={state.values.name} onChange={handleChange} />
<label htmlFor="email">이메일:</label>
<input type="email" id="email" name="email" value={state.values.email} onChange={handleChange} />
<button type="submit">제출</button>
</form>
);
};
2. useFormStatus
useFormStatus 훅은 Next.js 양식의 현재 상태 (예: 제출 중, 유효성 검사 실패)를 알려줍니다.
기능:
- 양식이 제출 중인지 확인합니다.
- 양식 유효성 검사가 실패했는지 확인합니다.
- 양식 오류 메시지를 가져옵니다.
사용 방법:
const MyForm = () => {
const { submitting, errors } = useFormStatus();
return (
<form>
{/* ... 양식 필드 ... */}
<button type="submit" disabled={submitting}>제출</button>
{errors && (
<div className="error-messages">
{Object.values(errors).map((error) => (
<p key={error}>{error}</p>
))}
</div>
)}
</form>
);
};
'TIL' 카테고리의 다른 글
Image Component (0) | 2024.06.20 |
---|---|
caching (0) | 2024.06.19 |
Suspense components (0) | 2024.06.14 |
SSR, React Server Components(RSC), Client Components (0) | 2024.06.12 |
createBrowserRouter, loader, action (0) | 2024.06.11 |