LoginSignup
4
1

More than 1 year has passed since last update.

《React.js&Next.js超入門 第2版》6章をFirebase JavaScript SDK v9で動かす その2

Last updated at Posted at 2022-02-17

《React.js&Next.js超入門 第2版》第6章のサンプルコードはFirebase JavaScript SDK v8 を用いて書かれています。
現在のバージョンは v9 であるため、そのままでは動きません。v9 で動くように修正します。

##6-4 Authでユーザー認証しよう
###リスト6-8

pages/fire/index.js
import { useState, useEffect } from 'react';
import Layout from '../../components/layout';
import '../../components/fire';
import { getAuth, GoogleAuthProvider, signInWithPopup } from 'firebase/auth';

const auth = getAuth();
const provider = new GoogleAuthProvider();

export default function Home() {
  const [message, setMessage] = useState('wait...');

  useEffect(() => {
    signInWithPopup(auth, provider).then(result => {
      setMessage('logined: ' + result.user.displayName);
    });
  }, []);

  return <>
    <Layout header="Next.js" title="Top page.">
      <div className="alert alert-primary text-center">
        <h5 className="mb-4">{message}</h5>
        <p className="h6 text-left">
          uid: {auth.currentUser != null ? auth.currentUser.uid : ''}<br />
          displayName: {auth.currentUser != null ? auth.currentUser.displayName : ''}<br />
          email: {auth.currentUser != null ? auth.currentUser.email : ''}<br />
          phoneNumber: {auth.currentUser != null ? auth.currentUser.phoneNumber : ''}
        </p>
      </div>
    </Layout>
  </>;
}

const auth = getAuth();でAuthオブジェクトを取得します。1
const provider = new GoogleAuthProvider;で認証プロバイダを作成します。
signInWithPopup(auth, provider)でポップアップでGoogle認証します。
その後の処理は書籍の通りです。

###リスト6-10

pages/fire/index.js
import { useState, useEffect } from 'react';
import Layout from '../../components/layout';
import '../../components/fire';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAuth, signOut, GoogleAuthProvider, signInWithPopup } from 'firebase/auth';

const db = getFirestore();
const auth = getAuth();
const provider = new GoogleAuthProvider();

signOut(auth);

export default function Home() {
  const mydata = [];
  const [data, setData] = useState(mydata);
  const [message, setMessage] = useState('wait...');

  useEffect(() => {
    signInWithPopup(auth, provider).then(result => {
      setMessage('logined: ' + result.user.displayName);
    }).catch(() => {
      setMessage('not logined.');
    });
  }, []);

  useEffect(() => {
    if (auth.currentUser != null) {
      getDocs(collection(db, 'mydata')).then(snapshot => {
        snapshot.forEach(document => {
          const doc = document.data();
          mydata.push(
            <tr key={document.id}>
              <td><a href={'/fire/del?id=' + document.id}>{document.id}</a></td>
              <td>{doc.name}</td>
              <td>{doc.mail}</td>
              <td>{doc.age}</td>
            </tr>
          );
        });
        setData(mydata);
      });
    } else {
      mydata.push(
        <tr key="1"><th colSpan="4">can&apos;t get data.</th></tr>
      );
    }
  }, [message]);

  return <>
    <Layout header="Next.js" title="Top page.">
      <div className="alert alert-primary text-center">
        <h5 className="mb-4">{message}</h5>
        <table className="table bg-white text-left">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Mail</th>
              <th>Age</th>
            </tr>
          </thead>
          <tbody>
            {data}
          </tbody>
        </table>
      </div>
    </Layout>
  </>;
}

signOut(auth);でログアウトします。
その他の処理は書籍の通りです。

###その他
前節で作成されたadd.jsdel.jsがこのままでは動作しませんでした。
以下のようにcomponents/fire.jsgetAuth()を追加すると動作しました。

components/fire.js
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  // 各プロジェクトの設定
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "..."
};

initializeApp(firebaseConfig);
getAuth();

##参考
React.js&Next.js超入門 第2版 サンプルコードのバグまとめ
《React.js&Next.js超入門 第2版》6章をFirebase JavaScript SDK v9で動かす その1
《React.js&Next.js超入門 第2版》6章をFirebase JavaScript SDK v9で動かす その3

  1. getAuth()の引数を指定しなかった場合は、名前が[DEFAULT]のアプリ情報が渡されたと判断するようです。アプリの名前はinitializeAppの第2引数で指定できます。指定しない場合は[DEFAULT]になります。

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1