์žฌ๋ฐŒ๊ฒŒ ํ•ฉ์‹œ๋‹ค

๊ธฐ๋กํ•˜๊ธฐ, ๊ฐ€์‹œํ™”ํ•˜๊ธฐ

React

react-hook-form ๋กœ๋”ฉ ํ™”๋ฉด ๋งŒ๋“ค๊ธฐ

์€๋˜๋”” 2022. 8. 22. 23:54

 

ํผ ์ œ์ถœ ํ›„ ์‘๋‹ต์ด ์˜ฌ ๋•Œ๊นŒ์ง€ ๋กœ๋”ฉ ํ™”๋ฉด์„ ๋„์›Œ๋ณด์ž.

 

๐ŸŽˆ ๊ธฐ์กด ๋ฐฉ์‹

๋ณดํ†ต React์—์„œ ๋กœ๋”ฉ ํ™”๋ฉด์„ ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ์‹์ผ ๊ฒƒ์ด๋‹ค.

function LoginPage() {

    const [loading, setLoading] = useState(null);
    return (
        <div>
        {loading && <Loading />}
        </div>
    )
}

 

submit ๋ฒ„ํŠผ ํด๋ฆญ โžก๏ธ setLoading(true) โžก๏ธ loading์˜ ์ƒํƒœ๊ฐ€ ๋ฐ”๋€Œ์–ด ๋ฆฌ๋ Œ๋”๋ง ๋ฐœ์ƒ, ๋กœ๋”ฉ UI๊ฐ€ ํ™”๋ฉด์— ๋„์›Œ์ง

 

๊ทธ๋Ÿฌ๋‚˜ react-hook-form์„ ์‚ฌ์šฉํ•œ ๊ฒฝ์šฐ ํ•ด๋‹น ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

react-hook-form ์‚ฌ์ดํŠธ์— ๋“ค์–ด๊ฐ€๋ณด๋ฉด, react-hook-form์€ form ์˜์—ญ์„ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ์˜์—ญ์˜ re-render๋ฅผ ๋ฐฉ์ง€ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค๊ณ  ์ ํ˜€์žˆ๋‹ค. ์ด๋•Œ๋ฌธ์— handleSubmit์— ๋“ฑ๋กํ•œ ํ•จ์ˆ˜ ๋‚ด์—์„œ setLoading์„ ํ†ตํ•ด ์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝํ•ด๋„, ๋ฆฌ๋ Œ๋”๋ง์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋”ฐ๋ผ์„œ ๋กœ๋”ฉ UI๊ฐ€ ๋ Œ๋”๋ง๋˜์ง€ ์•Š๋Š”๋‹ค.

 

โœ… formState - isSubmitting ํ™œ์šฉํ•˜๊ธฐ

๋‹คํ–‰ํžˆ react-hook-form์—์„œ๋Š” ๋กœ๋”ฉํ™”๋ฉด์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ„ํŽธํ•œ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•˜๊ณ  ์žˆ๋‹ค.

formState๋ฅผ ํ™œ์šฉํ•˜๋ฉด ๋œ๋‹ค. formState๋Š” ๋ง๊ทธ๋Œ€๋กœ ํผ์˜ ์ƒํƒœ ์ •๋ณด๊ฐ€ ์ €์žฅ๋˜์–ด ์žˆ๋Š” ๊ฐ์ฒด๋‹ค. ์•„๋ž˜์™€ ๊ฐ™์€ ์ •๋ณด๋“ค์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

  • isSubmitted
  • isSubmitSuccessful
  • isSubmitting
  • isValid
  • errors

react-hook-form formState ๊ณต์‹๋ฌธ์„œ

 

useForm - FormState

Performant, flexible and extensible forms with easy-to-use validation.

react-hook-form.com

์ž์„ธํ•œ ๋‚ด์šฉ์€ ๊ณต์‹ ๋ฌธ์„œ์—์„œ ํ™•์ธํ•˜์ž.

 

๋ฌดํŠผ ์ด ์ค‘์—์„œ ์šฐ๋ฆฐ isSubmitting์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค.

handleSubmit์— ๋“ฑ๋กํ•œ form ์ „์†ก ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋˜๋ฉด ๊ฐ’์ด true๊ฐ€ ๋œ๋‹ค. ํ•ด๋‹น ํ•จ์ˆ˜์˜ ๋น„๋™๊ธฐ ์ž‘์—…์ด ๋๋‚˜๊ณ  ์‘๋‹ต์„ ๋ฐ›์œผ๋ฉด false๋กœ ๋ฐ”๋€๋‹ค. (๊ณต์‹ ๋ฌธ์„œ์—๋Š” true if the form is currently being submitted. false otherwise. ๋ผ๊ณ  ๋˜์–ด ์žˆ๋‹ค.)

 

๋”ฐ๋ผ์„œ ์ด๋ ‡๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค.

function LoginPage() {
	const { register, handleSubmit, formState } = useForm();
    const { isSubmitting } = formState; // ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น
    return (
        <div>
        {isSubmitting && <Loading />}
        </div>
    )
}

๐Ÿ‘๐Ÿป ์™„์„ฑ ํ™”๋ฉด

์œ ์šฉ๋ณด์Šค react-hook-form