[React-Hook-Form] wrap-asycn

종인·2023년 5월 3일
0

문제점

form의 onSubmit이 실행되면 해당 내용의 페이지로 이동한다.

// index.tsx

const GraphqlMutationPage = () => {
  const { register, handleSubmit } = useForm<IFormData>();
  const onClickSubmit = async (data: IFormData) => {
    console.log(data);
  };

  console.log("리렌더링 되나요?");

  return (
    <form onSubmit={wrapAsync(handleSubmit(onClickSubmit))}>
      <input type="text" placeholder="작성자" {...register("writer")} />
      <br />
      <input type="text" placeholder="제목" {...register("title")} />
      <br />
      <input type="text" placeholder="내용" {...register("contents")} />
      <br />
      <input
        type="text"
        placeholder="주소"
        {...register("boardAddress.addressDetail")}
      />
      <br />
      <button>등록</button>
    </form>
  );
};
//asycnFunc.ts

export const wrapAsync = (asyncFunc: () => Promise<void>) => () => {
  void asyncFunc();
};

입력

결과

해결

위 같은 현상을 방지하기 위해 HTML의 form의 기능을 막아줄 필요가 있다. 이것을 막기 위해 event.preventDefault()를 사용한다.

// asyncFunc.ts

import type { FormEvent } from "react";

export const wrapFormAsync =
  (asyncFunc: () => Promise<void>) => (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    void asyncFunc();
};

입력

결과

페이지가 이동하지 않고 데이터를 정상적으로 보내졌다.

profile
어쩌면 오늘 하루는

0개의 댓글