Home > other >  Cannot retrieve user details and image in firebase vue
Cannot retrieve user details and image in firebase vue

Time:12-21

Good day. Please, I need help with my vue firebase code below. I can upload user details and image successfully but I am struggling with displaying the image on my vue component. The values return as undefined in Devtools. Please help me...

  methods: {
  async storeCourse() {
            try {
                this.isLoading = false
                // upload file
                const fileRef = 'uploads/courses/'   this.file.name
                const snapshot = await storage.ref(fileRef).put(this.file)
                let data = {
                    userId: auth.currentUser.uid,
                    subject: this.subject,
                    description: this.description,
                    tutor: this.tutor,
                    payment: this.payment,
                    duration: this.duration,
                    amount: this.amount,
                    years_exp: this.years_exp,
                    image: fileRef
                }
                window.alert('Added!')
                const docRef = coursesCollection.doc(); 
                data.id = docRef.id; 
                const doc = await docRef.set(data);
                // const doc = await coursesCollection.add(data)
                this.$emit('course:added', data)
                await this.resetForm()
                this.isLoading = false
                this.dialog = false
            } catch(e) {
                console.log(e)
            }
        },
async getUser() {
            try {
                // const querySnapshot = await coursesCollection.where('userId', '==', auth.currentUser.uid).get()
                const querySnapshot = await usersCollection.where('userId', '==', auth.currentUser.uid).get()
                querySnapshot.forEach( async (doc) => {
                    let img = ''
                    if(doc.data().id_upload) {
                        img = await storage.ref().child(doc.data().id_upload).getDownloadURL()
                    }
                    this.profile.push({
                        id_upload: img,
                        img: doc.data().id_upload
                    })
                })
            } catch(e) {
                console.log(e)
            }
        },
},
 async mounted() {
        await this.getGames()
                await this.getUser()

    }

I am trying to access the data in these ways:

<h1>Hi, {{profile.name}} </h1>
        
         <v-img :src="profile.id_upload"></v-img>

I have changed my getUser() to the code below, and it says the record is not found whereas the record exists alright.

 async getUser() {
            let ref = usersCollection.where('userId', '==', auth.currentUser.uid).get()
            .then(snapshot => {  //DocSnapshot
                if (snapshot.exists) {
                    let profile = snapshot.data()
                } else {
                    // snapshot.data() will be undefined in this case
                    console.log("No such document!");
                }  
            })
        },

Please where am I missing it?

CodePudding user response:

is there any reason why you dont just save the downloadURL to the firestore document directly when the user uploads a photo? then just get the url via the document instead of trying to get the downloadURL from the storage directly evertime?

edit: so the method you mention in your comment is just giving you the filepath. which is what you would use if you ever wanted to delete the photo. but the actual URL is a different value.

ill attach the code i use to upload to firebase storage and hopefully from there you can play around with it and get something working. i dont use Vue2 personally (started with VUE3) so the code might take some tweaking on your end. or modify the composable to work for you. hope this help.

 // my composable code

import { projectStorage } from "../firebase/config";
import { ref } from "vue";

const useStorage = () => {
  const error = ref(null);
  const imageUrl = ref(null);
  const imagefilePath = ref(null);

  const uploadImage = async (file) => {
    imagefilePath.value = 'uploads/courses/'   this.file.name';
    const storageRef = projectStorage.ref(imagefilePath.value);

    try {
      const res = await storageRef.put(file);
      ImageUrl.value = await res.ref.getDownloadURL();
    } catch (err) {
      console.log(err.message);
      error.value = err.message;
    }
  };

  return { imageUrl, imagefilePath, error, uploadImage };
};





//your code modified 

 async storeCourse() {
            try {
                this.isLoading = false
                // upload file
                
                let data = {
                    userId: auth.currentUser.uid,
                    subject: this.subject,
                    description: this.description,
                    tutor: this.tutor,
                    payment: this.payment,
                    duration: this.duration,
                    amount: this.amount,
                    years_exp: this.years_exp,
                    imagePath: this.imagefilePath,     
                    image: this.imageUrl, 
                }
                window.alert('Added!')
                const docRef = coursesCollection.doc(); 
                data.id = docRef.id; 
                const doc = await docRef.set(data);
                // const doc = await coursesCollection.add(data)
                this.$emit('course:added', data)
                await this.resetForm()
                this.isLoading = false
                this.dialog = false
            } catch(e) {
                console.log(e)
            }
        },

CodePudding user response:

there's potentially a few places where your code breaks down.

 async getUser() {
        let ref = usersCollection.where('userId', '==', auth.currentUser.uid).get()  //<-- are you sure auth.currentUser.uid returns a single string variable?
        .then(snapshot => {  //DocSnapshot
            if (snapshot.data()) {  //<-- change to this.
                let profile = {...snapshot.data(), id: snapshot.id} //<--and change to this
            } else {
                // snapshot.data() will be undefined in this case
                console.log("No such document!");
            }  
        })
    },

thats something to play around with.

  • Related