π° [React] react-hook-form μ μ¬μ©ν΄ μ€λ³΅ 체ν¬νκΈ°
μ?
λ―Έλ£¨κ³ λ―Έλ€λ νμκ°μ μ μ€λ³΅νμΈ λ‘μ§μ λ§λ€μ΄μΌνλ€.
(μμ£Ό κ°λ¨ν νμκ°μ
νΌμ λ¨Όμ λ§λ λ€)
νμ¬ 96TALK νλ‘μ νΈ λ΄μμλ react-hook-form
λΌμ΄λΈλ¬λ¦¬λ₯Ό μ¬μ© μ€μΈλ°
μ€λ³΅νμΈμ λλ² ν΄μΌ νλ μν©μ λμλ€.
μ΄λ©μΌ validation μ ν΅κ³Ό νμ λμλ§ Serverμ μ€λ³΅νμΈ μμ² ν μ μμκΉ?
μ€λμ ν΄λΉ λΌμ΄λΈλ¬λ¦¬μμ μ μ©ν trigger
λ₯Ό μκ°νλ €κ³ νλ€.
λΌμ΄λΈλ¬λ¦¬ μ€μΉ
1
npm install react-hook-form
μ¬μ© λ²
1
2
// Signup.tsx
const { trigger } = useForm();
trigger()
ν¨μλ₯Ό κ°μ Έμ¨λ€.trigger()
λ λΉλκΈ° ν¨μμ΄κΈ°μ κ·Έμ λ§κ²async ... await
μ κ±Έμ΄μ€λ€.argument
λ‘register
μμ λ±λ‘ν κ°μ λ£μ΄μ£Όλ©΄ ν΄λΉ input μ validation μ κ²μ¬νλ€.- κ²μ¬ ν ν΅κ³Όλ©΄ true, μ€ν¨λ©΄ false λ₯Ό λ°νν΄μ£Όλ―λ‘ λ°νκ°μΌλ‘ λ‘μ§ μ²λ¦¬
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
32
33
// Singup.tsx
const {
register,
handleSubmit,
formState: { errors },
setError,
getValues,
clearErrors,
trigger, // trigger ν¨μλ₯Ό κ°μ Έμ¨λ€
} = useForm<ISignupProps>();
const onDuplicateEmailCheck = async () => {
const target = getValues("memberEmail");
const isValid = await trigger("memberEmail");
if (isValid) {
// Validation μ±κ³΅ μ
try {
const response = await getDuplicateEmail(target);
// API μμ² ν μλ΅ κ° λ°κΈ°
if (response?.status === 200 && response?.data?.status === 200) {
// μ¬μ©κ°λ₯ ν λ©μΌμΌ κ²½μ°
setIsLoginMessage("μ¬μ©κ°λ₯ν μ΄λ©μΌ μ
λλ€.");
clearErrors("memberEmail");
}
} catch (error) {
setIsLoginMessage("μ€λ³΅λ μ΄λ©μΌ μ
λλ€.");
setError("memberEmail", { message: "νμκ°μ
μ‘°κ±΄μ΄ λ§μ§μμ΅λλ€." });
}
} else {
// Validation μ€ν¨ μ
}
};
λ§μΉλ©°
μμλ 곡μ λ¬Έμλ₯Ό λ€μ Έλ³΄λ©΄ λ€ λμ¨λ€β¦λ°±μ€λ μλ²μμλ
validation
μ νμ§λ§ μ΄μ€μ²λ¦¬λ₯Ό νλκ² κ°μ₯ μ’κΈ° λλ¬Έμμ€λ³΅νμΈ λ°λ‘ μ¬μ°¨ κ²μ¦ ν μ μλμ§ μμ보μλ€. κ²°κ΅μ μ±κ³΅.
This post is licensed under CC BY 4.0 by the author.