Home > Software engineering >  Trying to upload to firebase storage with react. TypeError: Cannot read properties of undefined (rea
Trying to upload to firebase storage with react. TypeError: Cannot read properties of undefined (rea

Time:12-01

Here is the below code. The console log tells me that it's correctly reading the image, but firebase.storage is undefined for some reason.

import React from 'react';
import firebase from 'firebase/compat/app';
import "firebase/storage";

function ProfilePic() {


    const [image , setImage] = React.useState('');

    const upload = ()=>{
    if (image == null) return;
        console.log(image);
        const ref = firebase.storage.ref(`images/${image.name}`);
        ref.put(image).on("state_changed" , alert("success") , alert);
        
    }
  
  return (
    <div className="App">
      <center>
      <input type="file" onChange={(e)=>{setImage(e.target.files[0])}}/>
      <button onClick={upload}>Upload</button>
      </center>
    </div>
  );
}

export default ProfilePic;

CodePudding user response:

You need to import the legacy namespaced library to use it how you are expecting.

import "firebase/compat/storage";

By using "firebase/storage", you end up importing the modern modular SDK instead.

You also need to use call firebase.storage() to get its instance rather than the namespace:

const ref = firebase.storage().ref(`images/${image.name}`);
  • Related