0
votes

How can I save the url for an image uploaded to Firebase Storage in Firebase Database?

When the code below runs I get this error:

Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field pfpURL in document users/HNJr68ZYXJXbA7v9n2jSHscXwSp1) at new ui (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:52471) at $f (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:177580) at Uf.ea (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:172230) at https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176225 at Gf (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176263) at https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176376 at Fr (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:45658) at Bf (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176351) at Mf (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:173339) at od.set (https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:263206)

HTML:

<div>
   <img id="profile-picture">
</div>

JS:

firebase.auth().onAuthStateChanged(function(user) {

var uid = firebase.auth().currentUser.uid

var fileButton = document.getElementById('choose-pfp');

fileButton.addEventListener('change', function(e) {

    var storageRef = firebase.storage().ref("profile_pictures/" + uid);

    var file = e.target.files[0];
    
    storageRef.put(file).then(function(snapshot) {

    window.alert("Profile picture has been uploaded!");



    storageRef.getDownloadURL().then(function(url) {
        document.querySelector('#profile-picture').src = url;

var url = storageRef.getDownloadURL();

        db.collection('users').doc(uid).set({
            pfpURL: url.value,
        
        })
    })
})
});
1

1 Answers

0
votes

You're calling getDownloadURL() for a second time inside your callback, which replaces the correct download URL with a promise.

The solution is to reuse the url that is passed into then():

storageRef.getDownloadURL().then(function(url) {
    document.querySelector('#profile-picture').src = url;

    db.collection('users').doc(uid).set({
        pfpURL: url,
    })
})