BigSteppaJC
BigSteppaJC

Reputation: 91

React Firebase image url not being saved

I want to upload images to FireBase storage and then save the image url to the firebase firestore database. It works 50% of the time but sometimes the url shows up as null.

CODE:

const onUpload = async () => {
    setLoading3(true);
    for (let i = 0; i < campaignImage.length; i += 1) {
    const file = campaignImage[i]
    const storageRef = storage.ref()
    const fileRef = storageRef.child(file.name)
    await fileRef.put(file)
    setUrl(await fileRef.getDownloadURL())
    
    db.collection("campaigns").doc(campaignName).update({
      images: firebase.firestore.FieldValue.arrayUnion({
        name: file.name,
        url: url
      })
      
    })
  }

The file name works perfectly but the url sometimes doesn't show. The image upload is always successful but placing the image url into the firestore collection is not working.

Upvotes: 0

Views: 619

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317828

It sounds like setUrl() is a react state hook. When you call it, it will not immediately affect the value of the variable it provides. If you need to use the URL from getDownloadURL(), you should save it to a local variable. The url from the state hook will get its new value after the component renders again.

    const downloadUrl = await fileRef.getDownloadURL())
    setUrl(downloadUrl)
    
    db.collection("campaigns").doc(campaignName).update({
      images: firebase.firestore.FieldValue.arrayUnion({
        name: file.name,
        url: downloadUrl
      })

Upvotes: 1

Related Questions