0
votes

In React Native, I select images using the ImagePicker package and upload images to Firebase Storage. I also want to send Firebase Storage image links using the Getdownloadurl() method with the Firebase Rest Api.

I manage to upload images, but when I send them by making a rest api post request, the image links go undefined. I'm following from the console screen making a post request without 100% of the total image size.

const uploadImage = async (uploadUri: string, transferred: number) => {
    let filename = uploadUri.substring(uploadUri.lastIndexOf('/') + 1);
    transferred = 0;
    const storageRef = storage().ref(`images/${filename}`);
    const task = storageRef.putFile(uploadUri);
    task.on('state_changed', taskSnapshot => {
        console.log(`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`);
        transferred = Math.round((taskSnapshot.bytesTransferred / taskSnapshot.totalBytes) * 100);
    });
    try {
        await task;
        const url = await storageRef.getDownloadURL();
        return url;
    } catch (error) {
        console.log(error);
        return null;
    }
}

export const addPost = (files: string[], post: Post): ThunkAction<void, RootState, null, AddPostAction> => {
    return async dispatch => {
        try {
            dispatch({ type: ADD_POST_LOADING, payload: true });
            const imageData: Image[] = [];
            files.map(async (item) => {
                const imageUrl = await uploadImage(item, 0);
                imageData.push({ image: imageUrl! });
            });
            const postData: Post = {
                ...post,
                thumb: imageData[0].image
            }
            const response = await fetch(`${BASE_URL}/post.json`, { method: "POST", body: JSON.stringify(postData) });
            if (response.ok) {
                const successPostData: AddPostSuccess = await response.json();
                dispatch({ type: ADD_POST_SUCCESS, payload: successPostData });
            } else {
                dispatch({ type: ADD_POST_ERROR, payload: "404" });
            }

        } catch (error) {
            console.log(error);
        }
    }
}
1

1 Answers

0
votes

A map can't handle async code. Try to change this part:

 files.map(async (item) => {
                const imageUrl = await uploadImage(item, 0);
                imageData.push({ image: imageUrl! });
            });

to this:

for (let i = 0; i < files.length; i++) {
              const item = files[i];
              const imageUrl = await uploadImage(item, 0);
                imageData.push({ image: imageUrl! }); 
            }