LoginSignup
1
0

More than 3 years have passed since last update.

Firebaseでユーザー認証を行うときのメソッド

Posted at

Firebese Authのメソッド

1. createUserWithEmailAndPassword()

文字通りメールアドレスとパスワード認証でユーザーを作成するメソッド
引数にemail,passwordを受け取る
戻り値はPromis

 .then(result => {
        const user = result.user

とするとuser.uidなどで取得しやすい

firestoreに登録する場合

if (user) {
          const uid = user.uid
          const timestamp = FirebaseTimestamp.now()
          const userInitialDate = {
            created_at: timestamp,
            email: email
            uid: uid,
            updated_at: timestamp,
            username: username
          }

          db.collection('users').doc(uid).set(userInitialDate)
            .then(() => {
              dispatch(push('/'))
            })
        }

とすることでusersコレクションに登録される。ちなみにdbの中身はfirebase.firestore()になっていて、処理が完了するとルートパスに戻る。

2.signInWithEmailAndPassword()

上記で作成したアカウントにログインするメソッド
引数にemail, passwordを受け取る
上記同様に実行結果を定数に入れることで扱いやすくなる
firebase Authでサインインした場合アプリ側にもstateを更新する必要があるので、以下のようにする

if (user) {
          const uid = user.uid

          db.collection("users").doc(uid).get()
            .then(snapshot => {
              const data =snapshot.data()

              dispatch(signInAction({
                isSignedIn: true,
                uid: uid,
                username: data.username
              }))
              dispatch(push("/"))
            })
        }

データベースからuidが一致する情報を引っ張り、signInActionを実行しreduxのstateを変更している(reduxではactionsは変更を伝える役割で実際にはreducersがどう変更するか決めている)

1
0
0

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
1
0