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 × Firebase】Firebaseでプロフィール情報を管理して、ユーザーの名前と画像を表示させる

Posted at

Firebaseでプロフィール情報を管理して、ユーザーの名前と画像を表示させる

signUp.vue

methods: {
    signUp() {
      let self = this;
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((userCredential) => {
          userCredential.user.updateProfile({
            //userCredential引数を渡して新規登録したユーザーをauthでプロフィール情報を登録。
            displayName: self.name,
            photoURL: require("../assets/デフォルト画像.jpg"),
          });
          //新規登録時に取得した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)
              .set({
                name: this.name,
                time: firebase.firestore.FieldValue.serverTimestamp(),
                uid: userCredential.user.uid,
              })
          );
        })
        .then(() => {
          this.$router.push(`/mypage/${this.uid}`);
          //新規登録後、「/mypage/userCredential.user.uid」で該当ページに遷移
        })
        .catch(() => {
          this.$swal("登録情報が正しくありません。", {
            icon: "error",
          });
        });
    },
  },
};
</script>

新規登録時(firebase.auth().createUserWithEmailAndPassword(this.email, this.password))に、
updateProfile()を使用して、displayNameとphotoURLを設定してあげる。

詳細は、公式リファレンス参照。
Firebase でユーザーを管理する

その後、displayNameをここでFirestoreに保存。

    signUp() {
      let self = this;
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then((userCredential) => {
          userCredential.user.updateProfile({
            //userCredential引数を渡して新規登録したユーザーをauthでプロフィール情報を登録。
            displayName: self.name,
            photoURL: require("../assets/デフォルト画像.jpg"),
          });
          this.$swal("登録に成功しました。", {
            icon: "success",
          });
          this.uid = userCredential.user.uid;
          //this.uidに 「userCredential.user.uid;」を格納
          return (
            firebase
              .firestore()
              .collection("users")
              .doc(userCredential.user.uid)
              .set({
                name: this.name,
                time: firebase.firestore.FieldValue.serverTimestamp(),
                uid: userCredential.user.uid,
              })
          );

mypage.vue

updateBtn() {
            this.$swal({
                title: "内容確認",
                text: "この内容で更新しますか?",
                icon: "info",
                buttons: true,
                dangerMode: true,
            }).then((willDelete) => {
                if (willDelete) {
                    let uploadParam = {};
                    if (this.uploadUrl) {
                        const uploadTask = firebase
                            .storage()
                            .ref(this.uploadUrl) //さっき決めたパスを参照して、
                            .put(this.file); //保存する
                        uploadTask.then(() => {
                            uploadTask.snapshot.ref.getDownloadURL().then((fileUrl) => {
                                //this.fileに保存されたrefを参照してファイルのダウンロード URL を取得して、fileUrlへ代入。
                                this.$set(this, "uploadedImage", {
                                    fileUrl: fileUrl,
                                    time: firebase.firestore.FieldValue.serverTimestamp(),
                                });
                                console.log(fileUrl, this.uploadUrl);
                                uploadParam = { uploadedImage: this.uploadedImage };
                                //uploadParamへuploadedImageを代入。
                                firebase
                                    //画像をfirestoreに保存
                                    .firestore()
                                    .collection("users") //保存する場所を参照して、
                                    .doc(this.$route.params.uid) //追加で保存setメソッドを使うと上書きされる
                                    .set(
                                        {
                                            name: this.name,
                                            sex: this.sex,
                                            age: this.age,
                                            access: this.access,
                                            selfpr: this.selfpr,
                                            profession: this.profession,
                                            genre: this.genre,
                                            favMovie: this.favMovie,
                                            ...uploadParam,
                                            time: firebase.firestore.FieldValue.serverTimestamp(),
                                            //サーバ側で値設定
                                        },
                                        { merge: true }
                                        //set()でmergeをtrueにすると、上書き。updetaと同様。
                                    );
                                const currentUser = firebase.auth().currentUser;
                                currentUser
                                    .updateProfile({
                                        photoURL: fileUrl,
                                    })
                                    .then(() => { })
                                .catch(()=>{
                                });
                            });
                        });
                    }
                    firebase
                        //画像をfirestoreに保存
                        .firestore()
                        .collection("users") //保存する場所を参照して、
                        .doc(this.$route.params.uid) //追加で保存setメソッドを使うと上書きされる
                        .set(
                            {
                                name: this.name,
                                sex: this.sex,
                                age: this.age,
                                access: this.access,
                                selfpr: this.selfpr,
                                profession: this.profession,
                                genre: this.genre,
                                favMovie: this.favMovie,
                                ...uploadParam,
                                time: firebase.firestore.FieldValue.serverTimestamp(),
                                //サーバ側で値設定
                            },
                            { merge: true }
                            //set()でmergeをtrueにすると、上書き。updetaと同様。
                        );
                    this.$swal("更新しました。", {
                        icon: "success",
                    });
                } else {
                    this.$swal("キャンセルしました。");
                }
            })
            .catch(() => {
              this.$swal("更新出来ませんでした。", {
                icon: "error",
              });
              this.preview = ""
              //更新をキャンセルした場合、空にする。
            });
        },

マイページにてプロフィール画像を編集する際に、上記にてFirestoreに保存後、
Firebaseでも下記にてphotoURLにfileUrlを保存させてあげる。

const currentUser = firebase.auth().currentUser;

  currentUser.updateProfile({
     photoURL: fileUrl,
  })

chat.vue

あとは表示させたいページにて以下コードにて名前は{{user.displayName}}として、displayNameを表示させ、
画像については、:src="user.photoURL"として、photoURL(fileUrl)を表示させる。

<div class="myimage flex">
  <img :src="user.photoURL" width="50" height="50" />
    <div class="myname flex">{{user.displayName}}</div>

Firebaseの構築にてAuthentication内でデータを確認しても、FiresoreやRealtimeDatabaseのように
displayNameとphotoURLが保存されている事は確認出来ない為、注意。

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?