Zach Sweedler
Zach Sweedler

Reputation: 33

Succesful image upload to Firebase Storage but file is named "undefined"

import React, {useState} from 'react';
import { storage } from '../../firebase';
import { ref, uploadBytes } from 'firebase/storage';

function AddImg() {

  const [imgUpload, setImgUpload] = useState(null);

  const uploadImg = () => {
    if (imgUpload == null) return;

    const imgRef = ref(storage, `listing_imgs/${imgUpload.name}`);
    uploadBytes(imgRef, imgUpload).then((snapshot) => {
      console.log('Image Uploaded');
    })
  };

  return (
    <>
      <input 
        type="file" 
        onChange={(event) => {
          setImgUpload(event.target.files)
        }}
      />
      <button onClick={uploadImg}>Add Image</button>
    </>
  )
}

export default AddImg;

Result of upload in Firebase

Every time I upload a new file, instead of firebase adding a new file to the bucket, the "undefined" file just gets updated (I can tell by the timestamp).

I've only tried uploading .pngs and .jpegs. I'm locally hosting my app and using Next.JS.

Does anyone know what's causing this to happen?

Upvotes: 0

Views: 747

Answers (1)

Yilmaz
Yilmaz

Reputation: 49341

  onChange={(event) => {
      setImgUpload(event.target.files)
    }}

event.target.files is an array. it should be event.target.files[0]

Upvotes: 1

Related Questions