kazumalab tech log

流行りとリラックマと嵐が大好きです。技術的ログ。

Firebase Day1

Firebase、今いろんなところで使われているGoogleが提供しているサービス。 昔むかしにUnityのデータ保存先としてRealtimeDatabaseを使ったことがあるが、もうわすれてしまった。 最近はReactとかにふれる機会が多いので、それをFirebaseのhostingに乗っけて見ようかと思った、ちょっとお試ししてみた。

なんかReactのプロジェクトをいい感じで作ってくれるコマンドがあるのでそれを打って見る。

$ npx create-react-app colors

今回は適当に色を組み合わせて保存するサービスを作ろうかなぁと思ったので、colorsにした。 まぁ特に意味はないんだけど。

$ cd colors
$ firebase init

firebase-cliは別途インストールした。 initで対話形式でプロジェクトに必要なjsonを吐き出してくれる。なるほど。 ちなみに、プロジェクトをFirebase上で作って、リージョンを指定しないとプロジェクト選択でエラーが出るのでWebでポチポチっと。 なるほどなぁ。 そこはこの上ではできないんだ..って感じ。その後、デプロイしてみる。

$ npm run build
$ firebase deploy

この2コマンドぐらいで行けるが、

Error: Cloud resource location is not set for this project but the operation you are attempting to perform in Cloud Firestore requires it

有効になっていないリソースがあればエラーになるっぽい。Web上でポチポチっと有効にしてみたらとりあえずOK。 今日はその後firebase Authenticationを利用してGoogleOauthのログインまで完了した。

FirebaseのAuthenticationを利用するところはこういう感じに書いた。

import React from 'react'
import './App.css';
import firebase from "./firebase-config"

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      user: null
    }
  }

  render() {
    return(
      <div>
        <h1>Hello! Colors.</h1>
        { !this.isLogin && <button onClick={this.login}>Login</button> }
        { this.isLogin && <p>{this.state.user.email}</p> }
      </div>
    )
  }

  componentDidMount() {
    firebase.auth().onAuthStateChanged((user) => {
      this.setState({ user })
    })
  }

  get isLogin() {
    return this.state.user && this.state.user.uid
  }

  login() {
    const provider = new firebase.auth.GoogleAuthProvider()
    firebase.auth().signInWithRedirect(provider)
  }
}

export default App;

これを ReactDOM.renderレンダリングしてあげればいいんだなぁ。 firebaseのAPIを呼び出すときに毎回認証が必要なので、firebase-config.jsのように書き出しておく。

import firebase from 'firebase/app'
import 'firebase/auth'

const config = {
  apiKey: "APIKEY",
  authDomain: "Domain",
  databaseURL: "databaseURL",
  projectId: "projectID",
  storageBucket: "bucket",
  messagingSenderId: "senderid1234",
  appId: "1:hogehoge:web:1234"
}

firebase.initializeApp(config)

export default firebase

ちなみにFirebaseのConfigのApiKeyはJSファイルに書き出されてしまう。これに対する答えは以下を見れば良さそうだ。

stackoverflow.com