Open20
個人開発
firebaseの導入
- firebase上でプロジェクトの作成
- npm install -g firebase-tools
- permission deniedというエラーがでる→sudo npm install -g firebase-toolsで解決
- firebase login
これでコマンドからfirebaseが使えるように。
Cloud Firestoreの導入
- firebaseの管理画面上でCloud Firestoreを開き、データベースを作成
- ロケーションはasia-northeast1(東京)
データベースとアプリの接続にトライ中
エラー発生
'firebase/app' does not contain a default export
compatを使ってimportしたらいけた。
import firebase from 'firebase/compat/app';
2021年の8月にfirebaseのversionが上がったらしく、compatが必要になった?
アプリにfirebaseを追加
- firebaseの管理画面上から</>をクリックし、必要情報(アプリ名)を入力
- 途中で出てくるconst firebaseConfigの中身を控えておく。
- コマンド上でnpm install firebase
- プロジェクト直下に.envファイルを設置し、firebaseConfigの内容を記載
REACT_APP_FIREBASE_APIKEY=""
REACT_APP_FIREBASE_DOMAIN=""
REACT_APP_FIREBASE_DATABASE=""
REACT_APP_FIREBASE_PROJECT_ID=""
REACT_APP_FIREBASE_STORAGE_BUCKET=""
REACT_APP_FIREBASE_SENDER_ID=""
REACT_APP_FIREBASE_APP_ID=""
- src配下にfirebase.jsを配置し、firebaseのinitコードを記載。
▼参考
Email・passwordでのユーザー登録(firebase Authentication)
firebase.jsにて以下を記述。
import 'firebase/compat/auth';
~
export const auth = firebaseApp.auth();
firebaseではcreateUserWithEmailAndPassword(email, password)というメソッドが用意されているので、あとはこれを記述するだけ。
*emailとpasswordはuseStateをつかって以下のようにすればOK
const [email, setEmail] = useState('')
~
<input id="email" type="email" value={email} onChange={(e) => {setEmail(e.target.value)}} placeholder="email"/>
Google認証の導入
firebase.jsに以下を記述
import { GoogleAuthProvider } from 'firebase/auth';
〜
export const provider = new GoogleAuthProvider();
ログインページのファイルに以下を記述
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { provider } from "../../firebase"
〜
function LoginPage() {
const signInGoogle = () => {
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
}
return(
<>
<h1>Loginページ</h1>
<form>
<button type="button" onClick={signInGoogle}>Google認証</button>
</form>
</>
)
};
Email・passwordでのログイン
//関数定義
const signInEmail = async () => {
await auth.signInWithEmailAndPassword(email, password)
alert("ログインしました")
}
//呼び出し
<form>
<h2>ログイン</h2>
<input id="username" type="text" value={username} onChange={(e) => {setUsername(e.target.value)}} placeholder="username"/><br/>
<input id="email" type="email" value={email} onChange={(e) => {setEmail(e.target.value)}} placeholder="email"/><br/>
<input id="password" type="password" value={password} onChange={(e) => {setPassword(e.target.value)}} placeholder="password"/>
<button type="button" onClick={
async () => {
try {
await signInEmail()
} catch (err) {
alert(err.message)
}
}}>Sign Up
</button><br/><br/>
</form>
react レンダリングされるタイミング
- stateが更新されたとき
- propsが更新されたとき
- 親コンポーネントが再レンダリングされた時
現在ログインしているユーザー情報の取得(firebase)
firebaseのAuthオブジェクトが持つonAuthStateChangedメソッドを使う
auth.onAuthStateChanged((authUser) => {
dispatch(
login({
uid: authUser.uid,
displayName: authUser.displayName
})
)
})
これを記述するとうまくレンダリングされる謎
const loginUser = useSelector(state => state.users)
メモ
投稿データにidいらないかも(ドキュメントにidがふられているため)