Refresh The Latest Image

I use firebase and when I upload an image and refresh it gives me the last image in my storage which is not always the newly uploaded image but I was wondering if there is a way to give me the most recent image I uploaded.

function Profile() {

  const allInputs = {imgUrl: ''}
  const [imageAsFile, setImageAsFile] = useState('')
  const [imageAsUrl, setImageAsUrl] = useState(allInputs)


  const handleImageAsFile = (e) => {
    const image = e.target.files[0]
    setImageAsFile(imageFile => (image))
}


  let tokenDetails = localStorage.getItem("token");
  let userResult = JSON.parse(tokenDetails)
  let email = userResult['user']['email']
  let name = userResult['user']['username']


  
  const imagesListRef = ref(storage, "images/");



  const handleFireBaseUpload = e => {
    e.preventDefault()
    console.log('start of upload')
    // async magic goes here...
    if(imageAsFile === '') {
      console.error(`not an image, the image file is a ${typeof(imageAsFile)}`)
    }
    const uploadTask = storage.ref(`/images/${imageAsFile.name}`).put(imageAsFile)
    //initiates the firebase side uploading 
    uploadTask.on('state_changed', 
    (snapShot) => {
      //takes a snap shot of the process as it is happening
      console.log(snapShot)
    }, (err) => {
      //catches the errors
      console.log(err)
    }, () => {
      // gets the functions from storage refences the image storage in firebase by the children
      // gets the download url then sets the image from firebase as the value for the imgUrl key:
      storage.ref('images').child(imageAsFile.name).getDownloadURL()
       .then(fireBaseUrl => {
         setImageAsUrl(prevObject => ({...prevObject, imgUrl: fireBaseUrl}))
       })
    })
  }
  
  console.log(imageAsUrl.imgUrl);

//this code handles refreshing the image gives me the last image in my firebase bucket
  useEffect(() => {
    const func = async() => {
      listAll(imagesListRef).then((response) => {
      let lastIndex = response.items.length-1;
      response.items.forEach((item, index) => {
        if (index === lastIndex) {
        getDownloadURL(item).then((url) => {
          setImageAsUrl(prevObject => ({...prevObject, imgUrl: url}))
        });
      }});
    });
     
    }
    func();
  }, []);

   
  return (
    <div className='App'>
    <Header/>
    <h1 className='name'>Hello there {name}</h1>
    <br />
    <br />
    <div class="proPic">
    <Avatar src={imageAsUrl.imgUrl} sx={{ width: 250, height: 250 }} />
    <input type="file" onChange={handleImageAsFile} />
    <button onClick={handleFireBaseUpload}>Submit</button>
    <div className='genrePreferences'>

    </div>
    <div className='email'>
    {email}
    </div>
    </div>
    </div>
  )
}

I haven’t used firebase/firestore in a long time but can’t you add a createdAt property and use that?

I see that this uses the firestore database but isn’t it more efficient to store images outside a database?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.