Home > Software engineering >  Can't get image url after upload a file to Firebase
Can't get image url after upload a file to Firebase

Time:03-22

I need some help. I have the following code example. I set the current image url to state, but I get it after a few renderings, so once I call it in onRequestHandler, I don't get it right after. Is there any way I can wait for him to get it?

const Component= () => {
const [url, setUrl] = useState('');

const uploadFile = async (file) => {
    if (!file) {
        return;
    }

    const storageRef = ref(storage, `/documents/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);
    
    uploadTask.on('state_changed', (snapshot) => {
        const prog = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
        setProgress(prog);
    },
        (err) => console.log(err),
        () => {
            getDownloadURL(uploadTask.snapshot.ref)
                // .then((url) => console.log(url));
                .then((url) => setUrl(prevState => url));
            }
    );
       }
    
const onRequestHandler = async (e) => {
    e.preventDefault();
    uploadFile('giving the file from form');
   // I need the image url here to set it to the current user.
}


return ({ <form onSubmit={onRequestHandler}> </form> })

CodePudding user response:

Since you're calling getDownloadURL in the client-side JavaScript ode, it only executes after the page has loaded. At that point there is no way to wait for an asynchronous operation to complete before rendering the page to your user.

Your rendering code will have to handle the case where the image URL isn't available yet, typically by not rendering the image in that case, or by rendering a placeholder image URL. Then when you call setUrl, the page will rerender and you can show the correct image URL.

CodePudding user response:

You can insert the function in a while loop and put a "try-catch" in it to try to get the image from Firebase. Inside the "try" function you can insert your function to show the image and a break to exit the while loop, and inside the "catch" you can use your function to show a placeholder image.

  • Related