個人的な備忘録です。
環境
- 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>
);
};