firebase v9 Authentication の変更で、苦戦したメモ

2021/12/18に公開約4,300字

概要:

firebase v9の変更で、旧版認証コードのエラー発生し、修正難航したメモとなります。

  • 今回は、typescriptです

構成

  • Firebase
  • react

参考のぺージ

https://firebase.google.com/docs/auth/web/start?hl=ja
  • ユーザー登録

https://gist.github.com/kuc-arc-f/076db83ad05d1e6a8a32451c3d6e7769
  • firebase読込, firebase.ts

  • firebase.auth() と書くとエラー、getAuth() で、修正できました
    authを、exportしておきます

firebase.ts
import { initializeApp } from 'firebase/app';

import { getAuth } from 'firebase/auth'

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_SENDER_ID,
};

initializeApp(firebaseConfig);
export const auth = getAuth();

  • 登録 SignUp.tsx
    auth.createUserWithEmailAndPassword と書くとエラー、
    createUserWithEmailAndPassword(auth, ...) に修正
SignUp.tsx
// firebase v9 auth, SignUp sample
import React from 'react';
import { useState } from 'react';
import {auth} from '../../firebase';
import { createUserWithEmailAndPassword } from 'firebase/auth'

const SignUp = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
console.log(email, password);
  const handleSubmit = (event: any) => {
    event.preventDefault();
    const { email, password } = event.target.elements;
    createUserWithEmailAndPassword(auth, email.value, password.value)
    .then(( userCredential) => {
      console.log('user created');
      console.log(userCredential)
    })
    .catch((error) => {
      alert(error.message)
      console.error(error)
    }); 
    console.log(email.value);
  };
  const handleChangeEmail = (event: any) => {
    setEmail(event.currentTarget.value);
  };
  const handleChangePassword = (event: any) => {
    setPassword(event.currentTarget.value);
  };

  return (
    <div>
      <h1>ユーザ登録</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>メールアドレス</label>
          <input
            name="email"
            type="email"
            placeholder="email"
            onChange={(event) => handleChangeEmail(event)}
          />
        </div>
        <div>
          <label>パスワード</label>
          <input
            name="password"
            type="password"
            placeholder="password"
            onChange={(event) => handleChangePassword(event)}
          />
        </div>
        <hr />
        <div>
          <button>登録</button>
        </div>
      </form>
    </div>
  );
};

export default SignUp;
  • ログイン Login.tsx

auth.createUserWithEmailAndPassword と書くとエラー
createUserWithEmailAndPassword(auth, ...) に修正

Login.tsx
import React from 'react';
//import { useState } from 'react';
import {auth} from '../../firebase';
//import { createUserWithEmailAndPassword } from 'firebase/auth'
import { signInWithEmailAndPassword } from 'firebase/auth'
import { Link } from 'react-router-dom';

const Login = () => {
  const handleSubmit = (event: any) => {
    event.preventDefault();
    
    const { email, password } = event.target.elements;
    signInWithEmailAndPassword(auth, email.value, password.value)
      .then((user) => {
        console.log('ログイン成功=', user.user.uid)
      })
      .catch((error) => {
        console.error(error)
      })    
  };

  return (
    <div>
      <h1>ログイン</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>メールアドレス</label>
          <input name="email" type="email" placeholder="email" />
        </div>
        <div>
          <label>パスワード</label>
          <input name="password" type="password" placeholder="password" />
        </div>
        <hr />
        <div>
          <button>ログイン</button>
        </div>
        <hr />
        <div>
          <Link to={'/signup'}><button>Register</button>
          </Link>
        </div>
      </form>
    </div>
  );
};

export default Login

  • signOut : ログアウト/アインアウト
import { signInWithEmailAndPassword, signOut, sendPasswordResetEmail } from 'firebase/auth'
....

  async clickLogout(){
    signOut(auth).then(()=>{
      console.log("ログアウトしました");
    })
    .catch( (error)=>{
      console.log(`ログアウト時にエラーが発生しました (${error})`);
    });
  }

....

Discussion

ログインするとコメントできます