Home > Blockchain >  Error while uploading image to firebase storage and text input to firestore simultaneously
Error while uploading image to firebase storage and text input to firestore simultaneously

Time:11-27

I want that when my form is submitted, the text input and file chosen should be uploaded to a firestore collection and firebase storage respectively. I can't understand why it is giving me errors.

here's my form:

<form onSubmit={postSubmitHandler}>
    <input type="text" ref={postTextRef}/>
    <input type="file"/>
    <button type="submit">Upload</button>
</form>

and here's my handler function:

function postSubmitHandler(e) {
    e.preventDefault();
    const file = e.target .files[0];

    console.log(file)

    if (!file) return;
    const sotrageRef = ref(storage, `posts/${file.name}`);
    const uploadTask = uploadBytesResumable(sotrageRef, file);

    uploadTask.on(
        "state_changed",
        (snapshot) => {
        const prog = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        setProgress(prog);
        },
        (error) => console.log(error),
        () => {
        getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            console.log("File available at", downloadURL);
            firestore.collection('posts').doc(currentUser.uid).set({
                imageURL: downloadURL,
                caption: postTextRef.current.value,
                postedAt: new Date(),
                likes: 0
            })
        });
       }
    ); 
  }

The error I am getting is:

 TypeError: Cannot read properties of undefined (reading '0')
  47 | 
  48 |  function postSubmitHandler(e) {
  49 |    e.preventDefault();
> 50 |    const file = e.target.files[0];
  51 |  ^  

Please help me correct this error or if there's another good way to do so please let me know.

CodePudding user response:

Since your postSubmitHandler is responding to the form being submitted, its e.target points to the form element - not to the input where the files are.

A quick fix:

const input = e.target.querySelector("input[type='file']");
const file = input.files[0];

The first line here selects the correct input from your form (e.target), which is then used to access the files that the user selected.

  • Related