作成日: 2023-10-09T08:31:38.445Z
前回は新規登録の機能を実際に実装して見ました。。
今回はログインの機能を作成していきます。
コードの内容は前回とほぼほぼ一緒です。
ここでお詫びですがサーバー側でミスが発覚しました。
ログイン機能の記事を2023年10月9日に直しました。
それ以前にやってくれた方は申し訳ありませんが、
サーバー側の修正をお願いいたします。
前回と変わりません。
なので画像は貼りません。
メールアドレスとパスワードを入力して前回と同じところに遷移するイメージです。
login部分の文言に以下を追加します。
notingAcount:"ユーザ登録されていません",
differentPassword:"パスワードが違います。",
alertMessage:"ユーザ登録がされていない、もしくはパスワードが違います。もう一度確認して見てください。"
loginApi:"http://localhost:8080/auth/login",
新規登録の時のAPIを作成したファイルの下に以下のコードを書きます。
ほとんど一緒ですが、書き換わっている部分がいくつかあるので注意してください。
//ログインのAPI送信 export const login=async(data:loginType)=>{ const res=await fetch(linkName.loginApi,{ method:"POST", headers:{ 'Content-Type':'application/json' }, body:JSON.stringify(data) }); const resJson=await res.json() if(resJson.data===ja.login.notingAcount||resJson.data===ja.login.differentPassword){ return []; }else{ return resJson.data as resAuthData[]; } }
前回は「signupForm」でしたが今回は「loginForm」です。
そこにonSubmitとあるはずなのでそこの関数を書き換えます。
const onSubmit=async(data:loginType)=>{ const res:resAuthData[]=await login(data); if(res.length===0){ alert(ja.login.alertMessage); }else{ router.push(`/todo?id=${res[0].id}&name=${res[0].name}`) } };
一応コードの全体像も載せておきます。
'use client'
import { loginValidation } from "@/shared/rules";
import { loginType, resAuthData } from "@/shared/type";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import styles from "./style.css";
import InputForm from "@/app/components/inputForm";
import ja from "@/shared/ja";
import SubmitButton from "@/app/components/submitButton";
import RoutingButton from "@/app/components/routingButton";
import linkName from "@/shared/linkName";
import { useRouter } from "next/navigation";
import { login } from "@/api/auth";
const LoginForm = () => {
const router=useRouter();
const { register,
handleSubmit,
formState:{errors}
} = useForm<loginType>({
resolver: yupResolver(loginValidation),
});
const onSubmit=async(data:loginType)=>{
const res:resAuthData[]=await login(data);
if(res.length===0){
alert(ja.login.alertMessage);
}else{
router.push(`/todo?id=${res[0].id}&name=${res[0].name}`)
}
};
return (
<div>
<div className={styles.inputText}>
<InputForm
labelName={ja.login.attribute.email.labelName}
register={register('email')}
error={'email' in errors}
helperText={errors.email?.message}
typeName={ja.login.attribute.email.typeName}
/>
</div>
<div className={styles.inputText}>
<InputForm
labelName={ja.login.attribute.password.labelName}
register={register('password')}
error={'password' in errors}
helperText={errors.password?.message}
typeName={ja.login.attribute.password.typeName}
/>
</div>
<div className={styles.inputButton}>
<SubmitButton
submitEvent={handleSubmit(onSubmit)}
buttonTitle={ja.login.buttonTitle}
/>
</div>
<div className={styles.inputButton}>
<RoutingButton
linkName={linkName.home}
linkTitle={ja.login.gobackBotton}
/>
</div>
</div>
);
}
export default LoginForm;
私のこの記事にて処理の漏れがなければ前回同様にログインができるかと思います。
todoの投稿、取得