0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue × Firestore】新規登録時に取得したuidを元にマイページにページ遷移させる

Last updated at Posted at 2021-04-30

新規登録時に取得したuidを元にマイページにページ遷移させる

signup.vue
<template>
  <div>
    <Header />
    <div class="signup flex">
      <div class="signup-inner flex">
        <h2>新規登録</h2>
        <input type="text" placeholder="Username" v-model="name" />
        <input type="text" placeholder="Email" v-model="email" />
        <input type="password" placeholder="Password" v-model="password" />
        <button class="btn-signup" @click.prevent="signUp">登録</button>
        <p>
          既に登録済みの方は
          <router-link to="/signin">こちらへ</router-link>
        </p>
      </div>
    </div>
  </div>
</template>
signup.vue
<script>
import firebase from "firebase";
import Header from "@/components/header.vue";

  ~ 省略 ~

export default {
  name: "Signup",
  data() {
    return {
      email: "",
      password: "",
      name: "",
      uid: "",
    };
  },
  components: {
    Header,
  },
  methods: {
    signUp() {
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((userCredential) => {
          //新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡す。
          this.$swal("登録に成功しました。", {
            icon: "success",
          });
          this.uid = userCredential.user.uid;
          //this.uidに 「userCredential.user.uid;」を格納
          return firebase
            .firestore()
            .collection("users")
            .doc(userCredential.user.uid)
            //usersのドキュメントを参照して、上記で引数として受けたuserCredentialのuid取得
            .set({
              name: this.name,
              time: firebase.firestore.FieldValue.serverTimestamp(),
              uid: userCredential.user.uid,
              //各マイページにページ遷移する為にuidをfirestoreに格納
            });
        })
        .then(() => {
          this.$router.push(`/mypage/${this.uid}`);
          //新規登録後、「/mypage/userCredential.user.uid」で該当ページに遷移
        })
        .catch(() => {
          this.$swal("登録情報が正しくありません。", {
            icon: "error",
          });
        });
    },
  },
};
</script>

まずfirebase.auth().createUserWithEmailAndPassword(this.email, this.password)で
新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡します。

signup.vue
    signUp() {
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((userCredential) => {
          //新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡す。
          this.$swal("登録に成功しました。", {
            icon: "success",
          });

usersというコレクションを参照して、上記で取得したuserCredential(ユーザー資格情報)から「uid」を取得して
set()を使ってuidをFirestoreにデータを追加。

signup.vue
    return firebase
            .firestore()
            .collection("users")
            .doc(userCredential.user.uid)
            //usersのドキュメントを参照して、上記で引数として受けたuserCredentialのuid取得
            .set({
              name: this.name,
              time: firebase.firestore.FieldValue.serverTimestamp(),
              uid: userCredential.user.uid,
              //各マイページにページ遷移する為にuidをfirestoreに格納
            });
        })

ページを遷移させる為に一度this.uidに 「userCredential.user.uid;」を格納してから
${this.uid}として対象ページに遷移させています。

signup.vue
         this.uid = userCredential.user.uid;
         //this.uidに 「userCredential.user.uid;」を格納

         ~ 省略 ~

        .then(() => {
          this.$router.push(`/mypage/${this.uid}`);
          //新規登録後、「/mypage/userCredential.user.uid」で該当ページに遷移
        })

uidはどこから取得している?

ちなみにthis.uid を取得している箇所は下記になります。

this.uid = userCredential.user.uid;

つまり、メールアドレスとパスワードでログインした人の、uid です。

引数に渡されたuserCredentialとは?

userCredential という名前自体は、利用者が勝手につけたものです。
別の名前、例えば abc にしても正しく動きますが、意味の分かるものにしているだけです。

変更前
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((userCredential) => {
          this.$swal("登録に成功しました。", {
            icon: "success",
          });
         this.uid = userCredential.user.uid;

変更後
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((abc) => {
          this.$swal("登録に成功しました。", {
            icon: "success",
          });
          this.uid = abc.user.uid;

渡される情報自体( userCredential の値や型)は、firebase が規定したものになります。
(つまり userCredential.user にユーザー情報が入っている、などは決められている)

公式サイト:Auth | JavaScript SDK | Firebase

上記ページを見ると、createUserWithEmailAndPassword は Promise を返すことがわかります。

直後の then の後の userCredential の型が UserCredential です。UserCredential の仕様は以下のページを見るとわかります。

公式サイト:auth | JavaScript SDK | Firebase

UserCredential の構造を以下のようになっていることがわかります。

{
   additionalUserInfo?: AdditionalUserInfo | null;
   credential: AuthCredential | null;
   operationType?: string | null;
   user: User | null
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?