やったこととか思ったこと

やったことを忘れないように気が向いたら書きます

firebaseでGoogle AuthEntication

firebaseのAuthEnticationを触ってわかったことのメモ。

src/firebase.ts

import * as firebase from "firebase/app";
import "firebase/auth";

const config = {
    // Project Overview -> アプリ -> 設定から
};

firebase.initializeApp(config);

export default firebase;

Auth.tsx

import * as React from "react";
import firebase from "./firebase";

const Auth: React.FC = () => {
    const [user, setUser] = React.useState<firebase.User | null>(null);
    
    React.useEffect(() => {
        const watcher = firebase.auth().onAuthStateChanged(user => {
          setUser(user)
        }
        return () => {
            watcher();
        }
    
    }, [setUser]);
    
    return(
        {user ?
        (
          <button onClick={() => firebase.auth().signOut()}>
            logout
          </button>
        ) : (
          <button onClick={login}>
            login
          </button>
        )
      }
    );
};

const login = () => {
  const provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider).then((result) => {
        // なんか処理
  }).catch(error => {
    // エラー処理
  });
};

export default Auth;

firebase.auth().onAuthStateChanged(…)firebase.auth().currentUserでも代用できるっぽい。

参考

https://firebase.google.com/docs/web/setup?authuser=0

https://firebase.google.com/docs/auth/web/start?authuser=0

https://firebase.google.com/docs/auth/web/manage-users?hl=ja

https://qiita.com/ossan-engineer/items/740425a0df937a47e093