LoginSignup
43
49

More than 1 year has passed since last update.

【React / Next】POST と PUT をカスタムフックで1つにまとめて、使用側はどちらかを意識しないようにする

Posted at

個人的な備忘録です。

環境

  • react: 17.0.2
  • react-hook-form: 7.28.0
  • next: 11.1.3

サンプルコード

postHandler
export const useProfileNew = () => {
  const { httpClient } = useHttpClient();

  const profileNewHandler = async (data: FormData) => {
    const requset: Request = {
      title: data.title,
      body: data.body,
    };

    const response = await httpClient.post<Response>(API_PATH);

    return response?.data;
  };

  return {
    profileNewHandler,
  };
};
putHandler
export const useProfileEdit = () => {
  const { httpClient } = useHttpClient();

  const profileEditHandler = async (data: FormData, id: string) => {
    const requset: Request = {
      title: data.title,
      body: data.body,
    };

    const response = await httpClient.put<Response>(
      `${API_PATH}/${id}`,
      request
    );

    return response?.data;
  };

  return {
    profileEditHandler,
  };
};
まとめるためのcustomHook
export const useProfileHandler = (isEdit: boolean) => {
  const { profileEditHandler } = useProfileEdit();
  const { profileNewHandler } = useProfileNew();

  const profileHandler = async (data: FormData, id: string) => {
    if (isEdit) {
      return await profileEditHandler(data, id);
    }
    return await profileNewHandler(data);
  };

  return {
    profileHandler,
  };
};
component
export const Component = () => {
  const { profileHandler } = useProfileHandler(isEdit);

  const onSubmit = async () => {
    // 使用側はどちらかを意識しなくて良い
    await profileHandler(data, id)
    reset();
  }

  // 省略

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* 省略 */}
      <button type={'submit'}>
        保存する
      </button>
    </form>
  );
};
43
49
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
49