【Firebase】Authenticationでログイン機能を実装する
Firebase

【Firebase】Authenticationでログイン機能を実装する

作成日:2022年02月11日
更新日:2022年02月12日

前回は、認証機能を設定するために、Authentication でユーザー登録しました。

firebase-authentication-signup

【Firebase】Authenticationでユーザー登録する

今回は、Authentication でログイン機能を実装します。

まずは、ログインのためのフックを作成します。

先日作成した、useAuth.js 内のuseSignupをコピーし、useLogin を作成します。

jsx
export const useLogin = () => {
const login = (email, password) => {
createUserWithEmailAndPassword(fireauth, email, password)
.then((res) => {
console.log(res.user);
})
.catch((err) => {
console.log(err.message);
});
};
return { login };
};

Firebase でログインをするために、firebase/authsignInWithEmailAndPasswordをインポートします。

jsx
import { signInWithEmailAndPassword } from "firebase/auth";

createUserWithEmailAndPasswordsignInWithEmailAndPasswordに書き換えます。

jsx
export const useLogin = () => {
const login = (email, password) => {
signInWithEmailAndPassword(fireauth, email, password)
.then((res) => {
console.log(res.user);
})
.catch((err) => {
console.log(err.message);
});
};
return { login };
};

次に、ログイン画面を作成します。

Login.js を作成しましょう。

Signup.js の内容をコピーし、Login用に編集します。

jsx
import React, { useState } from "react";
import { useLogin } from "../hooks/useAuth";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { login } = useLogin();
const handleSubmit = (e) => {
e.preventDefault();
login(email, password);
};
return (
<div>
<form onSubmit={handleSubmit} className="sign">
<div>
<label>Email: </label>
<input
required
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<label>Password: </label>
<input
required
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="button">
ログイン
</button>
</form>
</div>
);
};
export default Login;

一通り完成したので、ログイン画面でメールアドレスをパスワードを入力してみます。

まずは、登録していないメールアドレスを入力します。

image2

『ログイン』をクリックすると、

image3

Console にエラーメッセージが表示されました。

次は、登録したメールアドレスとパスワードを入力します。

image4

『ログイン』をクリックすると、

image5

Console に認証情報が表示されました。

次回は、Authentication でプロフィールを取得します。

firebase-authentication-profile-get

【Firebase】Authenticationでプロフィールを取得する

© 2024あずきぱんウェブスタジオ