Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ref._throwIfRoot is not a function (while trying to upload an image for Firebase Storage)

Based on the tutorial, I have exactly the same code but i am having problem while uploading the image. Every time I add the image and click upload i get an error which says :

reference.ts:290 Uncaught TypeError: ref._throwIfRoot is not a function
    at uploadBytesResumable$1 (reference.ts:290:1)
    at uploadBytesResumable (api.ts:164:1)
    at uploadFile (AddUser.jsx:22:1)
    at AddUser.jsx:49:1
    at commitHookEffectListMount (react-dom.development.js:23049:1)
    at commitPassiveMountOnFiber (react-dom.development.js:24816:1)
    at commitPassiveMountEffects_complete (react-dom.development.js:24781:1)
    at commitPassiveMountEffects_begin (react-dom.development.js:24768:1)
    at commitPassiveMountEffects (react-dom.development.js:24756:1)
    at flushPassiveEffectsImpl (react-dom.development.js:26990:1)

This is the code i have to add a new user with their credentials and image:

import { useEffect, useState } from 'react';
    import { doc, setDoc, addDoc, collection, serverTimestamp } from "firebase/firestore";
    import { createUserWithEmailAndPassword } from "firebase/auth"
    import { db, auth, storage } from '../../firebase';
    import { ref, uploadString, getDownloadURL, uploadBytesResumable } from "firebase/storage";
    


const New = ({ inputs, title }) => {

  const [file, setFile] = useState("");
  const [data, setData] = useState({});

  useEffect(() => {
    const uploadFile = () => {
      const name = new Date().getTime() + file.name;
      const storageRef = (storage, file.name);

      const uploadTask = uploadBytesResumable(storageRef, file);

      uploadTask.on('state_changed',
        (snapshot) => {
          const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log('Upload is ' + progress + '% done');
          switch (snapshot.state) {
            case 'paused':
              console.log('Upload is paused');
              break;
            case 'running':
              console.log('Upload is running');
              break;
            default: break;
          }
        },
        (error) => {
          console.log(error)
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            setData((prev) => ({ ...prev, img: downloadURL }))
          });
        }
      );

    }
    file && uploadFile();
  }, [file])

  const handleInput = (e) => {
    const id = e.target.id;
    const value = e.target.value;
    setData({ ...data, [id]: value })

  }

  const handleAddUser = async (e) => {
    e.preventDefault();

    try {
      const res = await createUserWithEmailAndPassword(auth, data.email, data.password);
      // Add a new user in collection
      await setDoc(doc(db, "users", res.user.uid), {
        ...data,
        timeStamp: serverTimestamp()
      });

    } catch (err) {
      console.log(err)
    }
  }

  return (
    <div className="new">
      <Sidebar />
      <div className="newContainer">
        <Navbar />
        <div className="top">
          <h1 className="title">{title}</h1>
        </div>
        <div className="bottom">
          <div className="left">
            <img src={file ? URL.createObjectURL(file) : "/images/default.jpg"} alt="" />
          </div>
          <div className="right">
            <form onSubmit={handleAddUser}>
              <div className="formInput">
                <label htmlFor="file">Upload Image</label>
                <input type="file" id="file" onChange={(e) => setFile(e.target.files[0])} />
              </div>
              {inputs.map((input) => (
                <div className="formInput" key={input.id}>
                  <label>{input.label}</label>
                  <input id={input.id} type={input.type} placeholder={input.placeholder} onChange={handleInput} />
                </div>
              ))}
              <button type="submit">SEND</button>
            </form>
          </div>
        </div>
      </div>
    </div >
  )
}

export default New

This is what I have in my firebase.js file. I have initialized firebaseConfig and all the necessary steps to upload a document to the collection. Also i have removed all the values for the firebaseConfig for security purpose.

import {
    initializeApp
} from "firebase/app";
import {
    getAuth
} from "firebase/auth";

import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";


// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();
export const storage = getStorage(app);
like image 387
Prakash Subba Avatar asked Aug 31 '25 11:08

Prakash Subba


1 Answers

Set the storage ref correctly:

const storageRef = ref(storage, file.name)
like image 139
erfan Avatar answered Sep 02 '25 23:09

erfan